Showing preview only (6,689K chars total). Download the full file or copy to clipboard to get everything.
Repository: yidao620c/python3-cookbook
Branch: master
Commit: 8c0b2ab251e0
Files: 827
Total size: 6.2 MB
Directory structure:
gitextract_xikm7pk_/
├── .gitignore
├── .travis.yml
├── Makefile
├── README.md
├── README_en.md
├── cookbook/
│ ├── __init__.py
│ ├── c01/
│ │ ├── __init__.py
│ │ ├── p03_nitem.py
│ │ ├── p04_nlargest.py
│ │ ├── p05_priority_queue.py
│ │ ├── p06_multidict.py
│ │ ├── p07_ordered_dict.py
│ │ ├── p08_calculate_dict.py
│ │ ├── p09_dict_common.py
│ │ ├── p10_remove_duplicate.py
│ │ ├── p11_naming_slice.py
│ │ ├── p12_mostfreq_items.py
│ │ ├── p13_sort_dictlist.py
│ │ ├── p14_sort_nocompare.py
│ │ ├── p15_group.py
│ │ ├── p16_filter.py
│ │ ├── p17_subdict.py
│ │ ├── p18_nameseq.py
│ │ ├── p19_trans_reduce.py
│ │ └── p20_combine_map.py
│ ├── c02/
│ │ ├── __init__.py
│ │ ├── p01_splitstr.py
│ │ ├── p02_str_start.py
│ │ ├── p03_unix_match.py
│ │ ├── p04_match_search.py
│ │ ├── p05_search_replace.py
│ │ ├── p06_case_insensitive.py
│ │ ├── p07_shortest_match.py
│ │ ├── p08_multiline_match.py
│ │ ├── p09_normal_unicode.py
│ │ ├── p10_re_unicode.py
│ │ ├── p11_strip.py
│ │ ├── p12_translate.py
│ │ ├── p13_align_str.py
│ │ ├── p14_join_str.py
│ │ ├── p15_var_string.py
│ │ ├── p16_textwrap.py
│ │ ├── p17_html_xml.py
│ │ ├── p18_tokenize.py
│ │ ├── p19_descent_parser.py
│ │ └── p20_byte_str.py
│ ├── c03/
│ │ ├── __init__.py
│ │ ├── p01_round.py
│ │ ├── p02_accurate_decimal.py
│ │ ├── p03_format_number.py
│ │ ├── p04_bin_octal.py
│ │ ├── p05_int_bytes.py
│ │ ├── p06_complex.py
│ │ ├── p07_inf_nan.py
│ │ ├── p08_fraction.py
│ │ ├── p09_array_numpy.py
│ │ ├── p10_matrix_linear.py
│ │ ├── p11_random_num.py
│ │ ├── p12_datatime.py
│ │ ├── p13_last_friday.py
│ │ ├── p14_month_range.py
│ │ ├── p15_str_datetime.py
│ │ └── p16_timezone.py
│ ├── c04/
│ │ ├── __init__.py
│ │ ├── p01_manual_iterator.py
│ │ ├── p02_delegate_iter.py
│ │ ├── p03_generator_pattern.py
│ │ ├── p04_iterator_protocol.py
│ │ ├── p05_reverse_iterate.py
│ │ ├── p06_generator_extrastate.py
│ │ ├── p07_iterator_slice.py
│ │ ├── p08_skip_iterable.py
│ │ ├── p09_iter_permutation.py
│ │ ├── p10_iterate_index.py
│ │ ├── p11_iterate_simultaneous.py
│ │ ├── p12_iterate_separate.py
│ │ ├── p13_process_pipline.py
│ │ ├── p14_flatten_sequence.py
│ │ ├── p15_merge_sorted.py
│ │ └── p16_iterate_while.py
│ ├── c05/
│ │ ├── __init__.py
│ │ ├── p01_rw_text.py
│ │ ├── p02_print_tofile.py
│ │ ├── p03_print_sepend.py
│ │ ├── p04_rw_binary.py
│ │ ├── p05_write_notexist.py
│ │ ├── p06_string_io.py
│ │ ├── p07_gzip_bz2.py
│ │ ├── p08_iterate_fixedsize.py
│ │ ├── p09_read_tobuffer.py
│ │ ├── p10_memery_mapping.py
│ │ ├── p11_pathnames.py
│ │ ├── p12_file_existence.py
│ │ ├── p13_dir_listfile.py
│ │ ├── p14_bypass_encode.py
│ │ ├── p15_print_badfile.py
│ │ ├── p16_change_opencode.py
│ │ ├── p17_bytes_tofile.py
│ │ ├── p18_file_descriptor.py
│ │ ├── p19_temp_file.py
│ │ ├── p20_serial_ports.py
│ │ └── p21_serialize_object.py
│ ├── c06/
│ │ ├── __init__.py
│ │ ├── data.json
│ │ ├── p01_rw_csv.py
│ │ ├── p02_rw_json.py
│ │ ├── p03_simple_xml.py
│ │ ├── p04_huge_xml.py
│ │ ├── p05_dict_toxml.py
│ │ ├── p06_rw_xml.py
│ │ ├── p07_namespace_xml.py
│ │ ├── p08_database.py
│ │ ├── p09_codec_hex.py
│ │ ├── p10_codec_base64.py
│ │ ├── p11_rw_barray.py
│ │ ├── p12_var_binary.py
│ │ ├── pred.xml
│ │ └── stocks.csv
│ ├── c07/
│ │ ├── __init__.py
│ │ ├── p02_keyarg_only.py
│ │ ├── p03_func_annotate.py
│ │ ├── p05_default_argument.py
│ │ ├── p06_anony_func.py
│ │ ├── p08_partial.py
│ │ ├── p09_class_to_func.py
│ │ ├── p10_callback.py
│ │ ├── p11_inline_callback.py
│ │ └── p12_closure_access.py
│ ├── c08/
│ │ ├── __init__.py
│ │ ├── p01_str_represent.py
│ │ ├── p02_custom_format.py
│ │ ├── p03_context_protocol.py
│ │ ├── p04_slots.py
│ │ ├── p05_encapsulate_name.py
│ │ ├── p06_managed_attribute.py
│ │ ├── p07_super_method.py
│ │ ├── p08_extend_property.py
│ │ ├── p09_descriptor.py
│ │ ├── p10_lazy_property.py
│ │ ├── p11_simplify_init.py
│ │ ├── p12_abstract_interface.py
│ │ ├── p13_type_system.py
│ │ ├── p14_custom_container.py
│ │ ├── p15_delegate_attribute.py
│ │ ├── p16_more_constructor.py
│ │ ├── p17_without_init.py
│ │ ├── p18_mixin_classes.py
│ │ ├── p19_stateful_object.py
│ │ ├── p20_invoke_bystr.py
│ │ ├── p21_vistor_pattern.py
│ │ ├── p22_vistor_norecursiion.py
│ │ ├── p23_weakref.py
│ │ ├── p24_class_compare.py
│ │ └── p25_cached_objects.py
│ ├── c09/
│ │ ├── __init__.py
│ │ ├── p01_wrap_function.py
│ │ ├── p02_preserve_metadata.py
│ │ ├── p03_unwrap_decorator.py
│ │ ├── p04_decorator_argument.py
│ │ ├── p05_adjust_attribute.py
│ │ ├── p06_optarg_decorator.py
│ │ ├── p07_typecheck.py
│ │ ├── p08_inclass_decorator.py
│ │ ├── p09_class_decorator.py
│ │ ├── p10_static_decorator.py
│ │ ├── p11_add_argument.py
│ │ ├── p12_patch_class.py
│ │ ├── p13_instance_create.py
│ │ ├── p14_attribute_order.py
│ │ ├── p15_meta_optional_arg.py
│ │ ├── p16_enforce_args.py
│ │ ├── p17_code_convention.py
│ │ ├── p18_define_classes.py
│ │ ├── p19_define_init.py
│ │ ├── p20_multiple_dispatch.py
│ │ ├── p21_avoid_repetitive.py
│ │ ├── p22_context_manager.py
│ │ ├── p23_local_side.py
│ │ ├── p24_analyze_source.py
│ │ └── p25_disassemble_bytecode.py
│ ├── c10/
│ │ ├── __init__.py
│ │ ├── p02_control_import.py
│ │ └── p12_import_patch.py
│ ├── c11/
│ │ ├── p01_.py
│ │ ├── p02_.py
│ │ ├── p03_.py
│ │ ├── p04_.py
│ │ ├── p05_.py
│ │ ├── p06_.py
│ │ ├── p07_.py
│ │ ├── p08_.py
│ │ ├── p09_.py
│ │ ├── p10_.py
│ │ ├── p11_.py
│ │ ├── p12_.py
│ │ └── p13_.py
│ ├── c12/
│ │ ├── __init__.py
│ │ ├── p01_start_stop_thread.py
│ │ ├── p02_.py
│ │ ├── p03_.py
│ │ ├── p04_.py
│ │ ├── p05_.py
│ │ ├── p06_.py
│ │ ├── p07_.py
│ │ ├── p08_.py
│ │ ├── p09_.py
│ │ ├── p10_.py
│ │ ├── p11_.py
│ │ ├── p12_.py
│ │ ├── p13_.py
│ │ └── p14_.py
│ ├── c13/
│ │ ├── p01_.py
│ │ ├── p02_.py
│ │ ├── p03_.py
│ │ ├── p04_.py
│ │ ├── p05_.py
│ │ ├── p06_.py
│ │ ├── p07_.py
│ │ ├── p08_.py
│ │ ├── p09_.py
│ │ ├── p10_.py
│ │ ├── p11_.py
│ │ ├── p12_.py
│ │ ├── p13_.py
│ │ ├── p14_.py
│ │ └── p15_.py
│ ├── c14/
│ │ ├── p01_.py
│ │ ├── p02_.py
│ │ ├── p03_.py
│ │ ├── p04_.py
│ │ ├── p05_.py
│ │ ├── p06_.py
│ │ ├── p07_.py
│ │ ├── p08_.py
│ │ ├── p09_.py
│ │ ├── p10_.py
│ │ ├── p11_.py
│ │ ├── p12_.py
│ │ ├── p13_.py
│ │ └── p14_.py
│ ├── c15/
│ │ ├── p01_.py
│ │ ├── p02_.py
│ │ ├── p03_.py
│ │ ├── p04_.py
│ │ ├── p05_.py
│ │ ├── p06_.py
│ │ ├── p07_.py
│ │ ├── p08_.py
│ │ ├── p09_.py
│ │ ├── p10_.py
│ │ ├── p11_.py
│ │ ├── p12_.py
│ │ ├── p13_.py
│ │ ├── p14_.py
│ │ ├── p15_.py
│ │ ├── p16_.py
│ │ ├── p17_.py
│ │ ├── p18_.py
│ │ ├── p19_.py
│ │ ├── p20_.py
│ │ └── p21_.py
│ └── somefile.txt
├── exts/
│ ├── chinese_search.py
│ ├── main.dic
│ ├── smallseg.py
│ ├── suffix.dic
│ └── zh.py
├── make.bat
├── notebook/
│ ├── fetch_cookbook.py
│ └── ipynb/
│ ├── 第一章:数据结构和算法/
│ │ ├── p01_unpack_sequence_into_separate_variables.ipynb
│ │ ├── p02_unpack_elements_from_iterables.ipynb
│ │ ├── p03_keep_last_n_items.ipynb
│ │ ├── p04_find_largest_or_smallest_n_items.ipynb
│ │ ├── p05_implement_a_priority_queue.ipynb
│ │ ├── p06_map_keys_to_multiple_values_in_dict.ipynb
│ │ ├── p07_keep_dict_in_order.ipynb
│ │ ├── p08_calculating_with_dict.ipynb
│ │ ├── p09_find_commonalities_in_dicts.ipynb
│ │ ├── p10_remove_duplicates_from_seq_order.ipynb
│ │ ├── p11_naming_slice.ipynb
│ │ ├── p12_determine_most_freqently_items_in_seq.ipynb
│ │ ├── p13_sort_list_of_dicts_by_key.ipynb
│ │ ├── p14_sort_objects_without_compare_support.ipynb
│ │ ├── p15_group_records_based_on_field.ipynb
│ │ ├── p16_filter_sequence_elements.ipynb
│ │ ├── p17_extract_subset_of_dict.ipynb
│ │ ├── p18_map_names_to_sequence_elements.ipynb
│ │ ├── p19_transform_and_reduce_data_same_time.ipynb
│ │ └── p20_combine_multiple_map_to_single_map.ipynb
│ ├── 第一章:数据结构和算法.ipynb
│ ├── 第七章:函数/
│ │ ├── p01_functions_that_accept_any_number_arguments.ipynb
│ │ ├── p02_functions_that_only_accept_keyword_arguments.ipynb
│ │ ├── p03_attach_informatinal_matadata_to_function_arguments.ipynb
│ │ ├── p04_return_multiple_values_from_function.ipynb
│ │ ├── p05_define_functions_with_default_arguments.ipynb
│ │ ├── p06_define_anonymous_or_inline_functions.ipynb
│ │ ├── p07_capturing_variables_in_anonymous_functions.ipynb
│ │ ├── p08_make_callable_with_fewer_arguments.ipynb
│ │ ├── p09_replace_single_method_classes_with_functions.ipynb
│ │ ├── p10_carry_extra_state_with_callback_functions.ipynb
│ │ ├── p11_inline_callback_functions.ipynb
│ │ └── p12_access_variables_defined_inside_closure.ipynb
│ ├── 第七章:函数.ipynb
│ ├── 第三章:数字日期和时间/
│ │ ├── p01_round_number.ipynb
│ │ ├── p02_accurate_decimal_calculations.ipynb
│ │ ├── p03_format_numbers_for_output.ipynb
│ │ ├── p04_binary_octal_hexadecimal_int.ipynb
│ │ ├── p05_pack_unpack_large_int_from_bytes.ipynb
│ │ ├── p06_complex_math.ipynb
│ │ ├── p07_infinity_and_nan.ipynb
│ │ ├── p08_calculating_with_fractions.ipynb
│ │ ├── p09_calculating_with_large_num_arrays.ipynb
│ │ ├── p10_matrix_and_linear_algebra_calculation.ipynb
│ │ ├── p11_pick_things_at_random.ipynb
│ │ ├── p12_convert_days_to_seconds_and_others.ipynb
│ │ ├── p13_determine_last_friday_date.ipynb
│ │ ├── p14_date_range_for_current_month.ipynb
│ │ ├── p15_convert_strings_into_datetimes.ipynb
│ │ └── p16_manipulate_dates_involving_timezone.ipynb
│ ├── 第三章:数字日期和时间.ipynb
│ ├── 第九章:元编程/
│ │ ├── p01_put_wrapper_around_function.ipynb
│ │ ├── p02_preserve_function_metadata_when_write_decorators.ipynb
│ │ ├── p03_unwrapping_decorator.ipynb
│ │ ├── p04_define_decorator_that_takes_arguments.ipynb
│ │ ├── p05_define_decorator_with_user_adjustable_attributes.ipynb
│ │ ├── p06_define_decorator_that_takes_optional_argument.ipynb
│ │ ├── p07_enforcing_type_check_on_function_using_decorator.ipynb
│ │ ├── p08_define_decorators_as_part_of_class.ipynb
│ │ ├── p09_define_decorators_as_classes.ipynb
│ │ ├── p10_apply_decorators_to_class_and_static_methods.ipynb
│ │ ├── p11_write_decorators_that_add_arguments_to_functions.ipynb
│ │ ├── p12_using_decorators_to_patch_class_definitions.ipynb
│ │ ├── p13_using_mataclass_to_control_instance_creation.ipynb
│ │ ├── p14_capture_class_attribute_definition_order.ipynb
│ │ ├── p15_define_metaclass_that_takes_optional_arguments.ipynb
│ │ ├── p16_enforce_argument_signature_on_args_kwargs.ipynb
│ │ ├── p17_enforce_coding_conventions_in_classes.ipynb
│ │ ├── p18_define_classes_programmatically.ipynb
│ │ ├── p19_initializing_class_members_at_definition_time.ipynb
│ │ ├── p20_implement_multiple_dispatch_with_function_annotations.ipynb
│ │ ├── p21_avoid_repetitive_property_methods.ipynb
│ │ ├── p22_define_context_managers_the_easy_way.ipynb
│ │ ├── p23_executing_code_with_local_side_effects.ipynb
│ │ ├── p24_parse_and_analyzing_python_source.ipynb
│ │ └── p25_disassembling_python_byte_code.ipynb
│ ├── 第九章:元编程.ipynb
│ ├── 第二章:字符串和文本/
│ │ ├── p01_split_string_on_multiple_delimiters.ipynb
│ │ ├── p02_match_text_at_start_end.ipynb
│ │ ├── p03_match_strings_with_shell_wildcard.ipynb
│ │ ├── p04_match_and_search_text.ipynb
│ │ ├── p05_search_and_replace_text.ipynb
│ │ ├── p06_search_replace_case_insensitive.ipynb
│ │ ├── p07_specify_regexp_for_shortest_match.ipynb
│ │ ├── p08_regexp_for_multiline_partterns.ipynb
│ │ ├── p09_normalize_unicode_text_to_regexp.ipynb
│ │ ├── p10_work_with_unicode_in_regexp.ipynb
│ │ ├── p11_strip_unwanted_characters.ipynb
│ │ ├── p12_sanitizing_clean_up_text.ipynb
│ │ ├── p13_aligning_text_strings.ipynb
│ │ ├── p14_combine_and_concatenate_strings.ipynb
│ │ ├── p15_interpolating_variables_in_strings.ipynb
│ │ ├── p16_reformat_text_to_fixed_number_columns.ipynb
│ │ ├── p17_handle_html_xml_in_text.ipynb
│ │ ├── p18_tokenizing_text.ipynb
│ │ ├── p19_writing_recursive_descent_parser.ipynb
│ │ └── p20_perform_text_operations_on_byte_string.ipynb
│ ├── 第二章:字符串和文本.ipynb
│ ├── 第五章:文件与IO/
│ │ ├── p01_read_write_text_data.ipynb
│ │ ├── p02_printing_to_file.ipynb
│ │ ├── p03_print_with_different_separator_or_line_ending.ipynb
│ │ ├── p04_read_write_binary_data.ipynb
│ │ ├── p05_write_to_file_not_exist.ipynb
│ │ ├── p06_io_operations_on_string.ipynb
│ │ ├── p07_read_write_compressed_datafiles.ipynb
│ │ ├── p08_iterate_over_fixed_sized_records.ipynb
│ │ ├── p09_read_binary_data_into_mutable_buffer.ipynb
│ │ ├── p10_memory_mapping_binary_files.ipynb
│ │ ├── p11_manipulating_pathnames.ipynb
│ │ ├── p12_test_for_the_existence_of_file.ipynb
│ │ ├── p13_get_directory_listing.ipynb
│ │ ├── p14_bypassing_filename_encoding.ipynb
│ │ ├── p15_printing_bad_filenames.ipynb
│ │ ├── p16_add_change_encoding_of_already_open_file.ipynb
│ │ ├── p17_write_bytes_to_text_file.ipynb
│ │ ├── p18_wrap_existing_file_descriptor_as_file_object.ipynb
│ │ ├── p19_make_temporary_files_and_directories.ipynb
│ │ ├── p20_communicating_with_serial_ports.ipynb
│ │ └── p21_serializing_python_objects.ipynb
│ ├── 第五章:文件与IO.ipynb
│ ├── 第八章:类与对象/
│ │ ├── p01_change_string_representation_of_instances.ipynb
│ │ ├── p02_customizing_string_formatting.ipynb
│ │ ├── p03_make_objects_support_context_management_protocol.ipynb
│ │ ├── p04_save_memory_when_create_large_number_instances.ipynb
│ │ ├── p05_encapsulating_names_in_class.ipynb
│ │ ├── p06_create_managed_attributes.ipynb
│ │ ├── p07_calling_method_on_parent_class.ipynb
│ │ ├── p08_extending_property_in_subclass.ipynb
│ │ ├── p09_create_new_kind_of_class_or_instance_attribute.ipynb
│ │ ├── p10_using_lazily_computed_properties.ipynb
│ │ ├── p11_simplify_initialization_of_data_structure.ipynb
│ │ ├── p12_define_interface_or_abstract_base_class.ipynb
│ │ ├── p13_implementing_data_model_or_type_system.ipynb
│ │ ├── p14_implementing_custom_containers.ipynb
│ │ ├── p15_delegating_attribute_access.ipynb
│ │ ├── p16_define_more_than_one_constructor_in_class.ipynb
│ │ ├── p17_create_instance_without_invoking_init_method.ipynb
│ │ ├── p18_extending_classes_with_mixins.ipynb
│ │ ├── p19_implements_stateful_objects_or_state_machines.ipynb
│ │ ├── p20_call_method_on_object_by_string_name.ipynb
│ │ ├── p21_implementing_visitor_pattern.ipynb
│ │ ├── p22_implementing_visitor_pattern_without_recursion.ipynb
│ │ ├── p23_managing_memory_in_cyclic_data_structures.ipynb
│ │ ├── p24_making_classes_support_comparison_operations.ipynb
│ │ └── p25_creating_cached_instances.ipynb
│ ├── 第八章:类与对象.ipynb
│ ├── 第六章:数据编码和处理/
│ │ ├── p01_read_write_csv_data.ipynb
│ │ ├── p02_read-write_json_data.ipynb
│ │ ├── p03_parse_simple_xml_data.ipynb
│ │ ├── p04_parse_huge_xml_files_incrementally.ipynb
│ │ ├── p05_turning_dictionary_into_xml.ipynb
│ │ ├── p06_parse_modify_rewrite_xml.ipynb
│ │ ├── p07_parse_xml_documents_with_namespaces.ipynb
│ │ ├── p08_interact_with_relational_database.ipynb
│ │ ├── p09_decode_encode_hexadecimal_digits.ipynb
│ │ ├── p10_decode_encode_base64.ipynb
│ │ ├── p11_read_write_binary_arrays_of_structures.ipynb
│ │ ├── p12_read_nested_and_variable_sized_binary_structures.ipynb
│ │ └── p13_summarizing_and_perform_statistics.ipynb
│ ├── 第六章:数据编码和处理.ipynb
│ ├── 第十一章:网络与Web编程/
│ │ ├── p01_interact_with_http_services_as_client.ipynb
│ │ ├── p02_creating_tcp_server.ipynb
│ │ ├── p03_creating_udp_server.ipynb
│ │ ├── p04_generate_range_of_ip_addresses_from_cidr_address.ipynb
│ │ ├── p05_creating_simple_rest_based_interface.ipynb
│ │ ├── p06_implement_simple_remote_procedure_call_with_xml_rpc.ipynb
│ │ ├── p07_communicate_simply_between_interpreters.ipynb
│ │ ├── p08_implementing_remote_procedure_calls.ipynb
│ │ ├── p09_authenticating_clients_simply.ipynb
│ │ ├── p10_add_ssl_to_network_services.ipynb
│ │ ├── p11_pass_socket_file_descriptor_between_processes.ipynb
│ │ ├── p12_understanding_event_driven_io.ipynb
│ │ └── p13_sending_receiving_large_arrays.ipynb
│ ├── 第十一章:网络与Web编程.ipynb
│ ├── 第十三章:脚本编程与系统管理/
│ │ ├── p01_accept_input_via_redirect_pips_or_input_files.ipynb
│ │ ├── p02_terminate_program_with_an_error_message.ipynb
│ │ ├── p03_parsing_command_line_options.ipynb
│ │ ├── p04_prompt_for_password_at_runtime.ipynb
│ │ ├── p05_getting_terminal_size.ipynb
│ │ ├── p06_executing_external_command_and_get_its_output.ipynb
│ │ ├── p07_copy_move_files_and_directories.ipynb
│ │ ├── p08_creating_and_unpacking_archives.ipynb
│ │ ├── p09_find_files_by_name.ipynb
│ │ ├── p10_read_configuration_files.ipynb
│ │ ├── p11_add_logging_to_simple_scripts.ipynb
│ │ ├── p12_add_logging_to_libraries.ipynb
│ │ ├── p13_making_stopwatch_timer.ipynb
│ │ ├── p14_putting_limits_on_memory_and_cpu_usage.ipynb
│ │ └── p15_luanch_a_web_browser.ipynb
│ ├── 第十三章:脚本编程与系统管理.ipynb
│ ├── 第十二章:并发编程/
│ │ ├── p01_start_stop_thread.ipynb
│ │ ├── p02_determining_if_thread_has_started.ipynb
│ │ ├── p03_communicating_between_threads.ipynb
│ │ ├── p04_locking_critical_sections.ipynb
│ │ ├── p05_locking_with_deadlock_avoidance.ipynb
│ │ ├── p06_storing_thread_specific_state.ipynb
│ │ ├── p07_creating_thread_pool.ipynb
│ │ ├── p08_perform_simple_parallel_programming.ipynb
│ │ ├── p09_dealing_with_gil_stop_worring_about_it.ipynb
│ │ ├── p10_defining_an_actor_task.ipynb
│ │ ├── p11_implement_publish_subscribe_messaging.ipynb
│ │ ├── p12_using_generators_as_alternative_to_threads.ipynb
│ │ ├── p13_polling_multiple_thread_queues.ipynb
│ │ └── p14_launching_daemon_process_on_unix.ipynb
│ ├── 第十二章:并发编程.ipynb
│ ├── 第十五章:C语言扩展/
│ │ ├── p01_access_ccode_using_ctypes.ipynb
│ │ ├── p02_write_simple_c_extension_module.ipynb
│ │ ├── p03_write_extension_function_operate_on_arrays.ipynb
│ │ ├── p04_manage_opaque_pointers_in_c_extension_modules.ipynb
│ │ ├── p05_define_and_export_c_api_from_extension_modules.ipynb
│ │ ├── p06_calling_python_from_c.ipynb
│ │ ├── p07_release_the_gil_in_c_extensions.ipynb
│ │ ├── p08_mix_threads_from_c_and_python.ipynb
│ │ ├── p09_wrap_c_code_with_swig.ipynb
│ │ ├── p10_wrap_existing_c_code_with_cython.ipynb
│ │ ├── p11_use_cython_to_write_high_performance_array_operation.ipynb
│ │ ├── p12_turning_function_pointer_into_callable.ipynb
│ │ ├── p13_pass_null_terminated_string_to_c_libraries.ipynb
│ │ ├── p14_pass_unicode_strings_to_c_libraries.ipynb
│ │ ├── p15_converting_c_string_to_python.ipynb
│ │ ├── p16_work_with_c_strings_of_dubious_encoding.ipynb
│ │ ├── p17_pass_filenames_to_c_extensions.ipynb
│ │ ├── p18_pass_open_files_to_c_extensions.ipynb
│ │ ├── p19_read_file_like_objects_from_c.ipynb
│ │ ├── p20_consuming_an_iterable_from_c.ipynb
│ │ └── p21_diagnosing_segmentation_faults.ipynb
│ ├── 第十五章:C语言扩展.ipynb
│ ├── 第十四章:测试、调试和异常/
│ │ ├── p01_testing_output_sent_to_stdout.ipynb
│ │ ├── p02_patching_objects_in_unit_tests.ipynb
│ │ ├── p03_testing_for_exceptional_conditions_in_unit_tests.ipynb
│ │ ├── p04_logging_test_output_to_file.ipynb
│ │ ├── p05_skip_or_anticipate_test_failures.ipynb
│ │ ├── p06_handle_multiple_exceptions.ipynb
│ │ ├── p07_catching_all_exceptions.ipynb
│ │ ├── p08_creating_custom_exceptions.ipynb
│ │ ├── p09_raise_exception_in_response_to_another_exception.ipynb
│ │ ├── p10_reraising_the_last_exception.ipynb
│ │ ├── p11_issuing_warning_messages.ipynb
│ │ ├── p12_debugging_basic_program_crashes.ipynb
│ │ ├── p13_profiling_and_timing_your_program.ipynb
│ │ └── p14_make_your_program_run_faster.ipynb
│ ├── 第十四章:测试、调试和异常.ipynb
│ ├── 第十章:模块与包/
│ │ ├── p01_make_hierarchical_package_of_modules.ipynb
│ │ ├── p02_control_the_import_of_everything.ipynb
│ │ ├── p03_import_submodules_by_relative_names.ipynb
│ │ ├── p04_split_module_into_multiple_files.ipynb
│ │ ├── p05_separate_directories_import_by_namespace.ipynb
│ │ ├── p06_reloading_modules.ipynb
│ │ ├── p07_make_directory_or_zip_runnable_as_main_script.ipynb
│ │ ├── p08_read_datafile_within_package.ipynb
│ │ ├── p09_add_directories_to_sys_path.ipynb
│ │ ├── p10_import_modules_using_name_given_in_string.ipynb
│ │ ├── p11_load_modules_from_remote_machine_by_hooks.ipynb
│ │ ├── p12_patching_modules_on_import.ipynb
│ │ ├── p13_installing_packages_just_for_yourself.ipynb
│ │ ├── p14_creating_new_python_environment.ipynb
│ │ └── p15_distributing_packages.ipynb
│ ├── 第十章:模块与包.ipynb
│ ├── 第四章:迭代器与生成器/
│ │ ├── p01_manually_consuming_iterator.ipynb
│ │ ├── p02_delegating_iteration.ipynb
│ │ ├── p03_create_new_iteration_with_generators.ipynb
│ │ ├── p04_implement_iterator_protocol.ipynb
│ │ ├── p05_iterating_in_reverse.ipynb
│ │ ├── p06_define_generator_func_with_extra_state.ipynb
│ │ ├── p07_taking_slice_of_iterator.ipynb
│ │ ├── p08_skip_first_part_of_iterable.ipynb
│ │ ├── p09_iterate_over_combination_or_permutation.ipynb
│ │ ├── p10_iterate_over_index_value_pairs_of_sequence.ipynb
│ │ ├── p11_iterate_over_multiple_sequences_simultaneously.ipynb
│ │ ├── p12_iterate_on_items_in_separate_containers.ipynb
│ │ ├── p13_create_data_processing_pipelines.ipynb
│ │ ├── p14_flattening_nested_sequence.ipynb
│ │ ├── p15_iterate_in_sorted_order_over_merged_sorted_iterables.ipynb
│ │ └── p16_replace_infinite_while_loops_with_iterator.ipynb
│ └── 第四章:迭代器与生成器.ipynb
├── requirements_.txt
└── source/
├── aboutme.rst
├── c01/
│ ├── p01_unpack_sequence_into_separate_variables.rst
│ ├── p02_unpack_elements_from_iterables.rst
│ ├── p03_keep_last_n_items.rst
│ ├── p04_find_largest_or_smallest_n_items.rst
│ ├── p05_implement_a_priority_queue.rst
│ ├── p06_map_keys_to_multiple_values_in_dict.rst
│ ├── p07_keep_dict_in_order.rst
│ ├── p08_calculating_with_dict.rst
│ ├── p09_find_commonalities_in_dicts.rst
│ ├── p10_remove_duplicates_from_seq_order.rst
│ ├── p11_naming_slice.rst
│ ├── p12_determine_most_freqently_items_in_seq.rst
│ ├── p13_sort_list_of_dicts_by_key.rst
│ ├── p14_sort_objects_without_compare_support.rst
│ ├── p15_group_records_based_on_field.rst
│ ├── p16_filter_sequence_elements.rst
│ ├── p17_extract_subset_of_dict.rst
│ ├── p18_map_names_to_sequence_elements.rst
│ ├── p19_transform_and_reduce_data_same_time.rst
│ └── p20_combine_multiple_map_to_single_map.rst
├── c02/
│ ├── p01_split_string_on_multiple_delimiters.rst
│ ├── p02_match_text_at_start_end.rst
│ ├── p03_match_strings_with_shell_wildcard.rst
│ ├── p04_match_and_search_text.rst
│ ├── p05_search_and_replace_text.rst
│ ├── p06_search_replace_case_insensitive.rst
│ ├── p07_specify_regexp_for_shortest_match.rst
│ ├── p08_regexp_for_multiline_partterns.rst
│ ├── p09_normalize_unicode_text_to_regexp.rst
│ ├── p10_work_with_unicode_in_regexp.rst
│ ├── p11_strip_unwanted_characters.rst
│ ├── p12_sanitizing_clean_up_text.rst
│ ├── p13_aligning_text_strings.rst
│ ├── p14_combine_and_concatenate_strings.rst
│ ├── p15_interpolating_variables_in_strings.rst
│ ├── p16_reformat_text_to_fixed_number_columns.rst
│ ├── p17_handle_html_xml_in_text.rst
│ ├── p18_tokenizing_text.rst
│ ├── p19_writing_recursive_descent_parser.rst
│ └── p20_perform_text_operations_on_byte_string.rst
├── c03/
│ ├── p01_round_number.rst
│ ├── p02_accurate_decimal_calculations.rst
│ ├── p03_format_numbers_for_output.rst
│ ├── p04_binary_octal_hexadecimal_int.rst
│ ├── p05_pack_unpack_large_int_from_bytes.rst
│ ├── p06_complex_math.rst
│ ├── p07_infinity_and_nan.rst
│ ├── p08_calculating_with_fractions.rst
│ ├── p09_calculating_with_large_num_arrays.rst
│ ├── p10_matrix_and_linear_algebra_calculation.rst
│ ├── p11_pick_things_at_random.rst
│ ├── p12_convert_days_to_seconds_and_others.rst
│ ├── p13_determine_last_friday_date.rst
│ ├── p14_date_range_for_current_month.rst
│ ├── p15_convert_strings_into_datetimes.rst
│ └── p16_manipulate_dates_involving_timezone.rst
├── c04/
│ ├── p01_manually_consuming_iterator.rst
│ ├── p02_delegating_iteration.rst
│ ├── p03_create_new_iteration_with_generators.rst
│ ├── p04_implement_iterator_protocol.rst
│ ├── p05_iterating_in_reverse.rst
│ ├── p06_define_generator_func_with_extra_state.rst
│ ├── p07_taking_slice_of_iterator.rst
│ ├── p08_skip_first_part_of_iterable.rst
│ ├── p09_iterate_over_combination_or_permutation.rst
│ ├── p10_iterate_over_index_value_pairs_of_sequence.rst
│ ├── p11_iterate_over_multiple_sequences_simultaneously.rst
│ ├── p12_iterate_on_items_in_separate_containers.rst
│ ├── p13_create_data_processing_pipelines.rst
│ ├── p14_flattening_nested_sequence.rst
│ ├── p15_iterate_in_sorted_order_over_merged_sorted_iterables.rst
│ └── p16_replace_infinite_while_loops_with_iterator.rst
├── c05/
│ ├── p01_read_write_text_data.rst
│ ├── p02_printing_to_file.rst
│ ├── p03_print_with_different_separator_or_line_ending.rst
│ ├── p04_read_write_binary_data.rst
│ ├── p05_write_to_file_not_exist.rst
│ ├── p06_io_operations_on_string.rst
│ ├── p07_read_write_compressed_datafiles.rst
│ ├── p08_iterate_over_fixed_sized_records.rst
│ ├── p09_read_binary_data_into_mutable_buffer.rst
│ ├── p10_memory_mapping_binary_files.rst
│ ├── p11_manipulating_pathnames.rst
│ ├── p12_test_for_the_existence_of_file.rst
│ ├── p13_get_directory_listing.rst
│ ├── p14_bypassing_filename_encoding.rst
│ ├── p15_printing_bad_filenames.rst
│ ├── p16_add_change_encoding_of_already_open_file.rst
│ ├── p17_write_bytes_to_text_file.rst
│ ├── p18_wrap_existing_file_descriptor_as_file_object.rst
│ ├── p19_make_temporary_files_and_directories.rst
│ ├── p20_communicating_with_serial_ports.rst
│ └── p21_serializing_python_objects.rst
├── c06/
│ ├── p01_read_write_csv_data.rst
│ ├── p02_read-write_json_data.rst
│ ├── p03_parse_simple_xml_data.rst
│ ├── p04_parse_huge_xml_files_incrementally.rst
│ ├── p05_turning_dictionary_into_xml.rst
│ ├── p06_parse_modify_rewrite_xml.rst
│ ├── p07_parse_xml_documents_with_namespaces.rst
│ ├── p08_interact_with_relational_database.rst
│ ├── p09_decode_encode_hexadecimal_digits.rst
│ ├── p10_decode_encode_base64.rst
│ ├── p11_read_write_binary_arrays_of_structures.rst
│ ├── p12_read_nested_and_variable_sized_binary_structures.rst
│ └── p13_summarizing_and_perform_statistics.rst
├── c07/
│ ├── p01_functions_that_accept_any_number_arguments.rst
│ ├── p02_functions_that_only_accept_keyword_arguments.rst
│ ├── p03_attach_informatinal_matadata_to_function_arguments.rst
│ ├── p04_return_multiple_values_from_function.rst
│ ├── p05_define_functions_with_default_arguments.rst
│ ├── p06_define_anonymous_or_inline_functions.rst
│ ├── p07_capturing_variables_in_anonymous_functions.rst
│ ├── p08_make_callable_with_fewer_arguments.rst
│ ├── p09_replace_single_method_classes_with_functions.rst
│ ├── p10_carry_extra_state_with_callback_functions.rst
│ ├── p11_inline_callback_functions.rst
│ └── p12_access_variables_defined_inside_closure.rst
├── c08/
│ ├── p01_change_string_representation_of_instances.rst
│ ├── p02_customizing_string_formatting.rst
│ ├── p03_make_objects_support_context_management_protocol.rst
│ ├── p04_save_memory_when_create_large_number_instances.rst
│ ├── p05_encapsulating_names_in_class.rst
│ ├── p06_create_managed_attributes.rst
│ ├── p07_calling_method_on_parent_class.rst
│ ├── p08_extending_property_in_subclass.rst
│ ├── p09_create_new_kind_of_class_or_instance_attribute.rst
│ ├── p10_using_lazily_computed_properties.rst
│ ├── p11_simplify_initialization_of_data_structure.rst
│ ├── p12_define_interface_or_abstract_base_class.rst
│ ├── p13_implementing_data_model_or_type_system.rst
│ ├── p14_implementing_custom_containers.rst
│ ├── p15_delegating_attribute_access.rst
│ ├── p16_define_more_than_one_constructor_in_class.rst
│ ├── p17_create_instance_without_invoking_init_method.rst
│ ├── p18_extending_classes_with_mixins.rst
│ ├── p19_implements_stateful_objects_or_state_machines.rst
│ ├── p20_call_method_on_object_by_string_name.rst
│ ├── p21_implementing_visitor_pattern.rst
│ ├── p22_implementing_visitor_pattern_without_recursion.rst
│ ├── p23_managing_memory_in_cyclic_data_structures.rst
│ ├── p24_making_classes_support_comparison_operations.rst
│ └── p25_creating_cached_instances.rst
├── c09/
│ ├── p01_put_wrapper_around_function.rst
│ ├── p02_preserve_function_metadata_when_write_decorators.rst
│ ├── p03_unwrapping_decorator.rst
│ ├── p04_define_decorator_that_takes_arguments.rst
│ ├── p05_define_decorator_with_user_adjustable_attributes.rst
│ ├── p06_define_decorator_that_takes_optional_argument.rst
│ ├── p07_enforcing_type_check_on_function_using_decorator.rst
│ ├── p08_define_decorators_as_part_of_class.rst
│ ├── p09_define_decorators_as_classes.rst
│ ├── p10_apply_decorators_to_class_and_static_methods.rst
│ ├── p11_write_decorators_that_add_arguments_to_functions.rst
│ ├── p12_using_decorators_to_patch_class_definitions.rst
│ ├── p13_using_mataclass_to_control_instance_creation.rst
│ ├── p14_capture_class_attribute_definition_order.rst
│ ├── p15_define_metaclass_that_takes_optional_arguments.rst
│ ├── p16_enforce_argument_signature_on_args_kwargs.rst
│ ├── p17_enforce_coding_conventions_in_classes.rst
│ ├── p18_define_classes_programmatically.rst
│ ├── p19_initializing_class_members_at_definition_time.rst
│ ├── p20_implement_multiple_dispatch_with_function_annotations.rst
│ ├── p21_avoid_repetitive_property_methods.rst
│ ├── p22_define_context_managers_the_easy_way.rst
│ ├── p23_executing_code_with_local_side_effects.rst
│ ├── p24_parse_and_analyzing_python_source.rst
│ └── p25_disassembling_python_byte_code.rst
├── c10/
│ ├── p01_make_hierarchical_package_of_modules.rst
│ ├── p02_control_the_import_of_everything.rst
│ ├── p03_import_submodules_by_relative_names.rst
│ ├── p04_split_module_into_multiple_files.rst
│ ├── p05_separate_directories_import_by_namespace.rst
│ ├── p06_reloading_modules.rst
│ ├── p07_make_directory_or_zip_runnable_as_main_script.rst
│ ├── p08_read_datafile_within_package.rst
│ ├── p09_add_directories_to_sys_path.rst
│ ├── p10_import_modules_using_name_given_in_string.rst
│ ├── p11_load_modules_from_remote_machine_by_hooks.rst
│ ├── p12_patching_modules_on_import.rst
│ ├── p13_installing_packages_just_for_yourself.rst
│ ├── p14_creating_new_python_environment.rst
│ └── p15_distributing_packages.rst
├── c11/
│ ├── p01_interact_with_http_services_as_client.rst
│ ├── p02_creating_tcp_server.rst
│ ├── p03_creating_udp_server.rst
│ ├── p04_generate_range_of_ip_addresses_from_cidr_address.rst
│ ├── p05_creating_simple_rest_based_interface.rst
│ ├── p06_implement_simple_remote_procedure_call_with_xml_rpc.rst
│ ├── p07_communicate_simply_between_interpreters.rst
│ ├── p08_implementing_remote_procedure_calls.rst
│ ├── p09_authenticating_clients_simply.rst
│ ├── p10_add_ssl_to_network_services.rst
│ ├── p11_pass_socket_file_descriptor_between_processes.rst
│ ├── p12_understanding_event_driven_io.rst
│ └── p13_sending_receiving_large_arrays.rst
├── c12/
│ ├── p01_start_stop_thread.rst
│ ├── p02_determining_if_thread_has_started.rst
│ ├── p03_communicating_between_threads.rst
│ ├── p04_locking_critical_sections.rst
│ ├── p05_locking_with_deadlock_avoidance.rst
│ ├── p06_storing_thread_specific_state.rst
│ ├── p07_creating_thread_pool.rst
│ ├── p08_perform_simple_parallel_programming.rst
│ ├── p09_dealing_with_gil_stop_worring_about_it.rst
│ ├── p10_defining_an_actor_task.rst
│ ├── p11_implement_publish_subscribe_messaging.rst
│ ├── p12_using_generators_as_alternative_to_threads.rst
│ ├── p13_polling_multiple_thread_queues.rst
│ └── p14_launching_daemon_process_on_unix.rst
├── c13/
│ ├── p01_accept_input_via_redirect_pips_or_input_files.rst
│ ├── p02_terminate_program_with_an_error_message.rst
│ ├── p03_parsing_command_line_options.rst
│ ├── p04_prompt_for_password_at_runtime.rst
│ ├── p05_getting_terminal_size.rst
│ ├── p06_executing_external_command_and_get_its_output.rst
│ ├── p07_copy_move_files_and_directories.rst
│ ├── p08_creating_and_unpacking_archives.rst
│ ├── p09_find_files_by_name.rst
│ ├── p10_read_configuration_files.rst
│ ├── p11_add_logging_to_simple_scripts.rst
│ ├── p12_add_logging_to_libraries.rst
│ ├── p13_making_stopwatch_timer.rst
│ ├── p14_putting_limits_on_memory_and_cpu_usage.rst
│ └── p15_luanch_a_web_browser.rst
├── c14/
│ ├── p01_testing_output_sent_to_stdout.rst
│ ├── p02_patching_objects_in_unit_tests.rst
│ ├── p03_testing_for_exceptional_conditions_in_unit_tests.rst
│ ├── p04_logging_test_output_to_file.rst
│ ├── p05_skip_or_anticipate_test_failures.rst
│ ├── p06_handle_multiple_exceptions.rst
│ ├── p07_catching_all_exceptions.rst
│ ├── p08_creating_custom_exceptions.rst
│ ├── p09_raise_exception_in_response_to_another_exception.rst
│ ├── p10_reraising_the_last_exception.rst
│ ├── p11_issuing_warning_messages.rst
│ ├── p12_debugging_basic_program_crashes.rst
│ ├── p13_profiling_and_timing_your_program.rst
│ └── p14_make_your_program_run_faster.rst
├── c15/
│ ├── p01_access_ccode_using_ctypes.rst
│ ├── p02_write_simple_c_extension_module.rst
│ ├── p03_write_extension_function_operate_on_arrays.rst
│ ├── p04_manage_opaque_pointers_in_c_extension_modules.rst
│ ├── p05_define_and_export_c_api_from_extension_modules.rst
│ ├── p06_calling_python_from_c.rst
│ ├── p07_release_the_gil_in_c_extensions.rst
│ ├── p08_mix_threads_from_c_and_python.rst
│ ├── p09_wrap_c_code_with_swig.rst
│ ├── p10_wrap_existing_c_code_with_cython.rst
│ ├── p11_use_cython_to_write_high_performance_array_operation.rst
│ ├── p12_turning_function_pointer_into_callable.rst
│ ├── p13_pass_null_terminated_string_to_c_libraries.rst
│ ├── p14_pass_unicode_strings_to_c_libraries.rst
│ ├── p15_converting_c_string_to_python.rst
│ ├── p16_work_with_c_strings_of_dubious_encoding.rst
│ ├── p17_pass_filenames_to_c_extensions.rst
│ ├── p18_pass_open_files_to_c_extensions.rst
│ ├── p19_read_file_like_objects_from_c.rst
│ ├── p20_consuming_an_iterable_from_c.rst
│ └── p21_diagnosing_segmentation_faults.rst
├── chapters/
│ ├── p01_data_structures_algorithms.rst
│ ├── p02_strings_and_text.rst
│ ├── p03_numbers_dates_times.rst
│ ├── p04_iterators_and_generators.rst
│ ├── p05_files_and_io.rst
│ ├── p06_data_encoding_and_process.rst
│ ├── p07_functions.rst
│ ├── p08_classes_and_objects.rst
│ ├── p09_meta_programming.rst
│ ├── p10_modules_and_packages.rst
│ ├── p11_network_and_web_program.rst
│ ├── p12_concurrency.rst
│ ├── p13_utility_script_and_system_manage.rst
│ ├── p14_test_debug_and_exceptions.rst
│ ├── p15_c_extensions.rst
│ └── p16_appendix.rst
├── conf.py
├── copyright.rst
├── index.rst
├── preface.rst
└── roadmap.rst
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
build/
.idea/
*.pyc
================================================
FILE: .travis.yml
================================================
language: python
cache: pip
python:
- 3.6
install:
- pip install flake8
before_script:
# stop the build if there are Python syntax errors or undefined names
- flake8 . --count --select=E901,E999,F821,F822,F823 --show-source --statistics
# exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
- flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
script:
- true
notifications:
on_success: change
on_failure: change # `always` will be the setting once code changes slow down
================================================
FILE: Makefile
================================================
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = build
# User-friendly check for sphinx-build
ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
endif
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " xml to make Docutils-native XML files"
@echo " pseudoxml to make pseudoxml-XML files for display purposes"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/python3-cookbook.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/python3-cookbook.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/python3-cookbook"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/python3-cookbook"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
latexpdfja:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through platex and dvipdfmx..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
xml:
$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
@echo
@echo "Build finished. The XML files are in $(BUILDDIR)/xml."
pseudoxml:
$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
@echo
@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
================================================
FILE: README.md
================================================
[](https://github.com/yidao620c/python3-cookbook/issues)
[![License][licensesvg]][license]
[](https://github.com/yidao620c/python3-cookbook/releases/latest)
[](https://github.com/yidao620c/python3-cookbook/releases)
# 《Python Cookbook in Chinese》 3rd Edition 翻译
《Python Cookbook》3rd 中文版3.0.0正式发布啦 ^_^! ——2017/12/07
在线阅读地址:<http://python3-cookbook.readthedocs.org/zh_CN/latest/>
最新版(3.0.0)下载
* 中文简体版PDF下载地址:<https://pan.baidu.com/s/1pL1cI9d>
* 中文繁体版PDF下载地址:<https://pan.baidu.com/s/1qX97VJI>
## 关于作者David Beazley
本书作者是David Beazley大神,一位独立的计算机科学家、教育家,以及有着35年开发经验的软件开发者。
他在Python社区一直都很活跃,编写了很多的[python包](http://www.dabeaz.com/software.html),
发表了很多的公开[演讲视频](http://www.dabeaz.com/talks.html) 以及
[编程教程](http://www.dabeaz.com/tutorials.html)。
同时还是[Python Essential Reference](http://www.dabeaz.com/per.html) 以及
[ Python Cookbook (O'Reilly Media)](http://www.dabeaz.com/cookbook.html)的作者。
David Beazley大神的博客地址:<http://www.dabeaz.com/>
## 译者的话
人生苦短,我用Python!
译者一直坚持使用Python3,因为它代表了Python的未来。虽然向后兼容是它的硬伤,但是这个局面迟早会改变的,
而且Python3的未来需要每个人的帮助和支持。
目前市面上的教程书籍,网上的手册大部分基本都是2.x系列的,专门基于3.x系列的书籍少的可怜。
最近看到一本《Python Cookbook》3rd Edition,完全基于Python3,写的也很不错。
为了Python3的普及,我也不自量力,想做点什么事情。于是乎,就有了翻译这本书的冲动了!
这不是一项轻松的工作,却是一件值得做的工作:不仅方便了别人,而且对自己翻译能力也是一种锻炼和提升。
译者会坚持对自己每一句的翻译负责,力求高质量。但受能力限制,也难免有疏漏或者表意不当的地方。
如果译文中有什么错漏的地方请大家见谅,也欢迎大家随时指正。
目前已经正式完成了整本书的翻译工作,历时2年,不管怎样还是坚持下来了。现在共享给python社区。
**欢迎关注我的个人公众号“飞污熊”,我会定期分享一些自己的Python学习笔记和心得。**

## 项目说明
* 所有文档均使用reStructuredText编辑,参考 [reStructuredText](http://docutils.sourceforge.net/docs/user/rst/quickref.html)
* 当前文档生成托管在 [readthedocs](https://readthedocs.org/) 上
* 生成的文档预览地址: [python3-cookbook](http://python3-cookbook.readthedocs.org/zh_CN/latest/)
* 使用了python官方文档主题 [sphinx-rtd-theme](https://github.com/snide/sphinx_rtd_theme) ,也是默认的主题default.
* 书中所有代码均在python 3.6版本下面运行通过,所有源码放在cookbook包下面
```
# on_rtd is whether we are on readthedocs.org, this line of code grabbed from docs.readthedocs.org
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
if not on_rtd: # only import and set the theme if we're building docs locally
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# otherwise, readthedocs.org uses their theme by default, so no need to specify it
```
## 其他贡献者
排名不分先后:
1. Yu Longjun (https://github.com/yulongjun)
1. tylinux (https://github.com/tylinux)
1. Kevin Guan (https://github.com/K-Guan)
1. littlezz (https://github.com/littlezz)
1. cclauss (https://github.com/cclauss)
1. Yan Zhang (https://github.com/Eskibear)
1. xiuyanduan (https://github.com/xiuyanduan)
1. FPlust (https://github.com/fplust)
1. lambdaplus (https://github.com/lambdaplus)
1. Tony Yang (liuliu036@gmail.com)
[更多贡献者](https://github.com/yidao620c/python3-cookbook/graphs/contributors)
-----------------------------------------------------
## 关于源码生成PDF文件
有网友提问怎样通过源码生成PDF文件,由于这个步骤介绍有点长,不适合放在README里面,
我专门写了篇博客专门介绍怎样通过ReadtheDocs托管文档,怎样自己生成PDF文件,大家可以参考一下。
<https://www.xncoding.com/2017/01/22/fullstack/readthedoc.html>
另外关于生成的PDF文件中会自动生成标题编号的问题,有热心网友 [CarlKing5019](https://github.com/CarlKing5019)提出了解决方案,
请参考issues108:
<https://github.com/yidao620c/python3-cookbook/issues/108>
再次感谢每一位贡献者。
-----------------------------------------------------
## How to Contribute
You are welcome to contribute to the project as follow
* fork project and commit pull requests
* add/edit wiki
* report/fix issue
* code review
* commit new feature
* add testcase
Meanwhile you'd better follow the rules below
* It's *NOT* recommended to submit a pull request directly to `master` branch. `develop` branch is more appropriate
* Follow common Python coding conventions
* Add the following [license] in each source file
## License
(The Apache License)
Copyright (c) 2014-2018 [Xiong Neng](<https://www.xncoding.com/>) and other contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.
[licensesvg]: https://img.shields.io/hexpm/l/plug.svg
[license]: http://www.apache.org/licenses/LICENSE-2.0
================================================
FILE: README_en.md
================================================
[](https://github.com/yidao620c/python3-cookbook/issues)
[![License][licensesvg]][license]
[](https://github.com/yidao620c/python3-cookbook/releases/latest)
[](https://github.com/yidao620c/python3-cookbook/releases)
Online reading address: http://python3-cookbook.readthedocs.org/zh_CN/latest/
The latest version (3.0.0) download
* Chinese simplified version PDF download address: https://pan.baidu.com/s/1pL1cI9d
* Chinese Traditional Chinese PDF download address: https://pan.baidu.com/s/1qX97VJI
## Translator's words
Life is short, I use Python!
The translator has always insisted on using Python 3 because it represents the future of Python. Although backward compatibility is its flaw, this situation will change sooner or later, and the future of Python3 needs everyone's help and support. At present, the tutorial books on the market, most of the manuals on the Internet are basically 2.x series, and the books based on the 3.x series are less pitiful.
Life is short, I use Python!
The translator has always insisted on using Python 3 because it represents the future of Python. Although backward compatibility is its hard injury, this situation will change sooner or later,
And the future of Python 3 needs everyone's help and support.
At present, the tutorial books on the market, most of the manuals on the Internet are basically 2.x series, and the books based on the 3.x series are less pitiful.
I recently saw a Python Cookbook 3rd Edition, based entirely on Python3, which is also very good.
For the popularity of Python3, I am not self-sufficient and want to do something. Ever since, there is an impulse to translate this book!
This is not an easy job, but it is a worthwhile job: it is not only convenient for others, but also an exercise and improvement for your ability to translate.
The translator will insist on being responsible for the translation of each sentence and strive for high quality. However, due to limited ability, it is inevitable that there will be omissions or improper expressions.
If there is anything wrong with the translation, please forgive me and welcome everyone to correct me.
At present, the translation of the entire book has been officially completed. It lasted for 2 years, and it persisted anyway. Now share it with the python community.
**Welcome to my personal public number "Flying Saffron Bear", I will share some of my own Python study notes and tips on a regular basis. **
[[Public Number] (https://github.com/yidao620c/python3-cookbook/raw/master/exts/wuxiong.jpg)
## project instruction
* All documents are edited using reStructuredText, refer to [reStructuredText] (http://docutils.sourceforge.net/docs/user/rst/quickref.html)
* Current document generation is hosted on [readthedocs] (https://readthedocs.org/)
* Generated document preview address: [python3-cookbook](http://python3-cookbook.readthedocs.org/zh_CN/latest/)
* Use the python official documentation theme [sphinx-rtd-theme] (https://github.com/snide/sphinx_rtd_theme), which is also the default theme default.
* All code in the book runs under Python 3.6, all source code is placed under the cookbook package
```
# on_rtd is whether we are on readthedocs.org, this line of code grabbed from docs.readthedocs.org
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
if not on_rtd: # only import and set the theme if we're building docs locally
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# otherwise, readthedocs.org uses their theme by default, so no need to specify it
```
## Other contributors
names not listed in order:
1. Yu Longjun (https://github.com/yulongjun)
1. tylinux (https://github.com/tylinux)
1. Kevin Guan (https://github.com/K-Guan)
1. littlezz (https://github.com/littlezz)
1. cclauss (https://github.com/cclauss)
1. Yan Zhang (https://github.com/Eskibear)
1. xiuyanduan (https://github.com/xiuyanduan)
1. FPlust (https://github.com/fplust)
1. lambdaplus (https://github.com/lambdaplus)
1. Tony Yang (liuliu036@gmail.com)
[More contributors] (https://github.com/yidao620c/python3-cookbook/graphs/contributors)
-------------------------------------------------- ---
## About source code generation PDF file
Some netizens asked how to generate a PDF file from the source code. Since this step is a bit long, it is not suitable for being placed in the README.
I wrote a blog dedicated to how to use the ReadtheDocs to host documents, how to generate PDF files yourself, you can refer to it.
<https://www.xncoding.com/2017/01/22/fullstack/readthedoc.html>
In addition, the issue of the title number is automatically generated in the generated PDF file, and the enthusiastic user [CarlKing5019] (https://github.com/CarlKing5019) proposes a solution.
Please refer to issues108:
<https://github.com/yidao620c/python3-cookbook/issues/108>
Thanks again to each contributor.
-----------------------------------------------------
## How to Contribute
You are welcome to contribute to the project as follow
* fork project and commit pull requests
* add/edit wiki
* report/fix issue
* code review
* commit new feature
* add testcase
Meanwhile you'd better follow the rules below
* It's *NOT* recommended to submit a pull request directly to `master` branch. `develop` branch is more appropriate
* Follow common Python coding conventions
* Add the following [license] in each source file
## License
(The Apache License)
Copyright (c) 2014-2018 [Xiong Neng](<https://www.xncoding.com/>) and other contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.
[licensesvg]: https://img.shields.io/hexpm/l/plug.svg
[license]: http://www.apache.org/licenses/LICENSE-2.0
================================================
FILE: cookbook/__init__.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: sample
Desc :
"""
================================================
FILE: cookbook/c01/__init__.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: sample
Desc :
"""
================================================
FILE: cookbook/c01/p03_nitem.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: collections.deque演示
Desc : deque有一个maxlen参数,当append的时候,如果超过,那么最前面的就被挤出队列。
"""
from collections import deque
def search(lines, pattern, history=5):
previous_lines = deque(maxlen=history)
for li in lines:
if pattern in li:
yield li, previous_lines
previous_lines.append(li)
# Example use on a file
if __name__ == '__main__':
with open(r'../../cookbook/somefile.txt') as f:
for line, prevlines in search(f, 'Python', 5):
for pline in prevlines:
print(pline, end='')
print(line, end='')
print('-' * 20)
================================================
FILE: cookbook/c01/p04_nlargest.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 返回集合中最大或最小的N个元素
Desc :
"""
import heapq
def main():
portfolio = [
{'name': 'IBM', 'shares': 100, 'price': 91.1},
{'name': 'AAPL', 'shares': 50, 'price': 543.22},
{'name': 'FB', 'shares': 200, 'price': 21.09},
{'name': 'HPQ', 'shares': 35, 'price': 31.75},
{'name': 'YHOO', 'shares': 45, 'price': 16.35},
{'name': 'ACME', 'shares': 75, 'price': 115.65}
]
cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price'])
expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price'])
print(cheap)
print(expensive)
nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
heapq.heapify(nums)
print(nums)
print(heapq.heappop(nums))
print(heapq.heappop(nums))
print(heapq.heappop(nums))
if __name__ == '__main__':
main()
================================================
FILE: cookbook/c01/p05_priority_queue.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 优先级队列
Desc :
"""
import heapq
class PriorityQueue:
def __init__(self):
self._queue = []
self._index = 0
def push(self, item, priority):
heapq.heappush(self._queue, (-priority, self._index, item))
self._index += 1
def pop(self):
return heapq.heappop(self._queue)[-1]
================================================
FILE: cookbook/c01/p06_multidict.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 多值映射
Desc :
"""
from collections import defaultdict
def multi_dict():
d = defaultdict(list)
d['a'].append(1)
d['a'].append(2)
d['b'].append(4)
d = defaultdict(set)
d['a'].add(1)
d['a'].add(2)
d['b'].add(4)
d = {} # A regular dictionary
d.setdefault('a', []).append(1)
d.setdefault('a', []).append(2)
d.setdefault('b', []).append(4)
================================================
FILE: cookbook/c01/p07_ordered_dict.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 排序字典
Desc :
"""
from collections import OrderedDict
d = OrderedDict()
d['foo'] = 1
d['bar'] = 2
d['spam'] = 3
d['grok'] = 4
# Outputs "foo 1", "bar 2", "spam 3", "grok 4"
for key in d:
print(key, d[key])
================================================
FILE: cookbook/c01/p08_calculate_dict.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 字典的数据运算
Desc :
"""
def calc_dict():
prices = {
'ACME': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
'FB': 10.75
}
min_price = min(zip(prices.values(), prices.keys()))
# min_price is (10.75, 'FB')
max_price = max(zip(prices.values(), prices.keys()))
# max_price is (612.78, 'AAPL')
prices_sorted = sorted(zip(prices.values(), prices.keys()))
# prices_sorted is [(10.75, 'FB'), (37.2, 'HPQ'),
# (45.23, 'ACME'), (205.55, 'IBM'),
# (612.78, 'AAPL')]
prices_and_names = zip(prices.values(), prices.keys())
print(min(prices_and_names)) # OK
print(max(prices_and_names)) # ValueError: max() arg is an empty sequence
min(prices) # Returns 'AAPL'
max(prices) # Returns 'IBM'
min(prices, key=lambda k: prices[k]) # Returns 'FB'
max(prices, key=lambda k: prices[k]) # Returns 'AAPL'
min_value = prices[min(prices, key=lambda k: prices[k])]
prices = { 'AAA' : 45.23, 'ZZZ': 45.23 }
min(zip(prices.values(), prices.keys()))
# (45.23, 'AAA')
max(zip(prices.values(), prices.keys()))
# (45.23, 'ZZZ')
================================================
FILE: cookbook/c01/p09_dict_common.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 字典的集合操作
Desc :
"""
def dict_commonality():
a = {
'x': 1,
'y': 2,
'z': 3
}
b = {
'w': 10,
'x': 11,
'y': 2
}
# Find keys in common
print(a.keys() & b.keys()) # { 'x', 'y' }
# Find keys in a that are not in b
print(a.keys() - b.keys()) # { 'z' }
# Find (key,value) pairs in common
print(a.items() & b.items()) # { ('y', 2) }
print(type(a.items()))
for a, b in a.items():
print(a, b)
if __name__ == '__main__':
dict_commonality()
================================================
FILE: cookbook/c01/p10_remove_duplicate.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 消除序列重复值并保持顺序
Desc :
"""
def dedupe(items):
"""元素都是hashable"""
seen = set()
for item in items:
if item not in seen:
yield item
seen.add(item)
def dedupe2(items, key=None):
"""元素不是hashable的时候"""
seen = set()
for item in items:
val = item if key is None else key(item)
if val not in seen:
yield item
seen.add(val)
def remove_dup():
a = [1, 5, 2, 1, 9, 1, 5, 10]
print(list(dedupe(a)))
a = [{'x': 1, 'y': 2}, {'x': 1, 'y': 3}, {'x': 1, 'y': 2}, {'x': 2, 'y': 4}]
print(list(dedupe2(a, key=lambda d: (d['x'], d['y']))))
print(list(dedupe2(a, key=lambda d: d['x'])))
if __name__ == '__main__':
remove_dup()
================================================
FILE: cookbook/c01/p11_naming_slice.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 命名切片
Desc :
"""
def name_slice():
record = '....................100 .......513.25 ..........'
cost = int(record[20:23]) * float(record[31:37])
SHARES = slice(20, 23)
PRICE = slice(31, 37)
cost = int(record[SHARES]) * float(record[PRICE])
print(cost)
print(SHARES.start)
print(SHARES.stop)
print(SHARES.step)
a = slice(5, 50, 2)
s = 'HelloWorld'
print(a.indices(len(s)))
for i in range(*a.indices(len(s))):
print(s[i])
if __name__ == '__main__':
name_slice()
================================================
FILE: cookbook/c01/p12_mostfreq_items.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 查找出现次数最多的元素
Desc :
"""
def most_freqency():
words = [
'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
'my', 'eyes', "you're", 'under'
]
from collections import Counter
word_counts = Counter(words)
# 出现频率最高的3个单词
top_three = word_counts.most_common(3)
print(top_three)
# Outputs [('eyes', 8), ('the', 5), ('look', 4)]
if __name__ == '__main__':
most_freqency()
================================================
FILE: cookbook/c01/p13_sort_dictlist.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 排序dict列表
Desc :
"""
def sort_dictlist():
rows = [
{'fname': 'Brian', 'lname': 'Jones', 'uid': 1003},
{'fname': 'David', 'lname': 'Beazley', 'uid': 1002},
{'fname': 'John', 'lname': 'Cleese', 'uid': 1001},
{'fname': 'Big', 'lname': 'Jones', 'uid': 1004}
]
from operator import itemgetter
rows_by_fname = sorted(rows, key=itemgetter('fname'))
rows_by_uid = sorted(rows, key=itemgetter('uid'))
print(rows_by_fname)
print(rows_by_uid)
rows_by_lfname = sorted(rows, key=itemgetter('lname','fname'))
print(rows_by_lfname)
if __name__ == '__main__':
sort_dictlist()
================================================
FILE: cookbook/c01/p14_sort_nocompare.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 排序不支持原生比较操作的对象
Desc :
"""
class User:
def __init__(self, user_id):
self.user_id = user_id
def __repr__(self):
return 'User({})'.format(self.user_id)
def sort_notcompare():
users = [User(23), User(3), User(99)]
print(users)
print(sorted(users, key=lambda u: u.user_id))
from operator import attrgetter
print(sorted(users, key=attrgetter('user_id')))
# print(sorted(users, key=attrgetter('last_name', 'first_name')))
print(min(users, key=attrgetter('user_id')))
print(max(users, key=attrgetter('user_id')))
if __name__ == '__main__':
sort_notcompare()
================================================
FILE: cookbook/c01/p15_group.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 分组迭代
Desc :
"""
from operator import itemgetter
from itertools import groupby
def group_iter():
rows = [
{'address': '5412 N CLARK', 'date': '07/01/2012'},
{'address': '5148 N CLARK', 'date': '07/04/2012'},
{'address': '5800 E 58TH', 'date': '07/02/2012'},
{'address': '2122 N CLARK', 'date': '07/03/2012'},
{'address': '5645 N RAVENSWOOD', 'date': '07/02/2012'},
{'address': '1060 W ADDISON', 'date': '07/02/2012'},
{'address': '4801 N BROADWAY', 'date': '07/01/2012'},
{'address': '1039 W GRANVILLE', 'date': '07/04/2012'},
]
# Sort by the desired field first
rows.sort(key=itemgetter('date'))
# Iterate in groups
for date, items in groupby(rows, key=itemgetter('date')):
print(date)
for i in items:
print(' ', i)
# defaultdict使用
from collections import defaultdict
rows_by_date = defaultdict(list)
for row in rows:
rows_by_date[row['date']].append(row)
if __name__ == '__main__':
group_iter()
================================================
FILE: cookbook/c01/p16_filter.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 序列元素过滤
Desc :
"""
from itertools import compress
def cb_filter():
mylist = [1, 4, -5, 10, -7, 2, 3, -1]
print([n for n in mylist if n > 0])
print([n for n in mylist if n < 0])
pos = (n for n in mylist if n > 0)
print(pos)
for x in pos:
print(x, end=',')
print()
values = ['1', '2', '-3', '-', '4', 'N/A', '5']
def is_int(val):
try:
x = int(val)
return True
except ValueError:
return False
ivals = list(filter(is_int, values))
print(ivals)
# Outputs ['1', '2', '-3', '4', '5']
# 条件过滤
clip_neg = [n if n > 0 else 0 for n in mylist]
print(clip_neg)
addresses = [
'5412 N CLARK',
'5148 N CLARK',
'5800 E 58TH',
'2122 N CLARK',
'5645 N RAVENSWOOD',
'1060 W ADDISON',
'4801 N BROADWAY',
'1039 W GRANVILLE',
]
counts = [ 0, 3, 10, 4, 1, 7, 6, 1]
more5 = [n > 5 for n in counts]
print(list(compress(addresses, more5)))
if __name__ == '__main__':
cb_filter()
================================================
FILE: cookbook/c01/p17_subdict.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: dict子集
Desc :
"""
def sub_dict():
prices = {
'ACME': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
'FB': 10.75
}
# Make a dictionary of all prices over 200
p1 = {key: value for key, value in prices.items() if value > 200}
# Make a dictionary of tech stocks
tech_names = {'AAPL', 'IBM', 'HPQ', 'MSFT'}
p2 = {key: value for key, value in prices.items() if key in tech_names}
if __name__ == '__main__':
sub_dict()
================================================
FILE: cookbook/c01/p18_nameseq.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 通过名称访问序列
Desc :
"""
from collections import namedtuple
def name_seq():
subscriber = namedtuple('Subscriber', ['addr', 'joined'])
sub = subscriber('jonesy@example.com', '2012-10-19')
print(sub)
print(sub.addr, sub.joined)
print(len(sub))
addr, joined = sub
print(addr, joined)
def compute_cost(records):
total = 0.0
for rec in records:
total += rec[1] * rec[2]
return total
def compute_cost2(records):
Stock = namedtuple('SSS', ['name', 'shares', 'price'])
total = 0.0
for rec in records:
st = Stock(*rec)
total += st.shares * st.price
s = Stock('ACME', 100, 123.45)
# 更新命名元组
s = s._replace(shares=75)
print(s)
return total
Stock1 = namedtuple('Stock', ['name', 'shares', 'price', 'date', 'time'])
# Create a prototype instance
stock_prototype = Stock1('', 0, 0.0, None, None)
# Function to convert a dictionary to a Stock
def dict_to_stock(s):
return stock_prototype._replace(**s)
def default_stock():
a = {'name': 'ACME', 'shares': 100, 'price': 123.45}
print(dict_to_stock(a))
b = {'name': 'ACME', 'shares': 100, 'price': 123.45, 'date': '12/17/2012'}
print(dict_to_stock(b))
if __name__ == '__main__':
name_seq()
# rs = [('aa', 12, 33)]
rs = [['aa', 12, 33]] # 元组和序列都可以
print(compute_cost2(rs))
default_stock()
================================================
FILE: cookbook/c01/p19_trans_reduce.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 转换并聚集函数
Desc :
"""
import os
def trans_reduce():
nums = [1, 2, 3, 4, 5]
s = sum(x * x for x in nums)
print(s)
files = os.listdir('dirname')
if any(name.endswith('.py') for name in files):
print('There be python!')
else:
print('Sorry, no python.')
# Output a tuple as CSV
s = ('ACME', 50, 123.45)
print(','.join(str(x) for x in s))
# Data reduction across fields of a data structure
portfolio = [
{'name':'GOOG', 'shares': 50},
{'name':'YHOO', 'shares': 75},
{'name':'AOL', 'shares': 20},
{'name':'SCOX', 'shares': 65}
]
min_shares = min(s['shares'] for s in portfolio)
# Original: Returns 20
min_shares = min(s['shares'] for s in portfolio)
# Alternative: Returns {'name': 'AOL', 'shares': 20}
min_shares = min(portfolio, key=lambda s: s['shares'])
if __name__ == '__main__':
trans_reduce()
================================================
FILE: cookbook/c01/p20_combine_map.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 合并多个字典或映射
Desc :
"""
from collections import ChainMap
def combine_map():
a = {'x': 1, 'z': 3 }
b = {'y': 2, 'z': 4 }
c = ChainMap(a,b)
print(c['x']) # Outputs 1 (from a)
print(c['y']) # Outputs 2 (from b)
print(c['z']) # Outputs 3 (from a)
print(len(c))
print(list(c.keys()))
print(list(c.values()))
c['z'] = 10
c['w'] = 40
del c['x']
print(a)
# del c['y']
values = ChainMap()
values['x'] = 1
# Add a new mapping
values = values.new_child()
values['x'] = 2
# Add a new mapping
values = values.new_child()
values['x'] = 3
print(values)
print(values['x'])
# Discard last mapping
values = values.parents
print(values['x'])
# Discard last mapping
values = values.parents
print(values['x'])
print(values)
if __name__ == '__main__':
combine_map()
================================================
FILE: cookbook/c02/__init__.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: sample
Desc :
"""
================================================
FILE: cookbook/c02/p01_splitstr.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 正则式分割字符串
Desc :
"""
import re
def split_str():
line = 'asdf fjdk; afed, fjek,asdf, foo'
print(re.split(r'[;,\s]\s*', line))
print(re.split(r'(;|,|\s)\s*', line))
fields = re.split(r'(;|,|\s)\s*', line)
values = fields[::2]
delimiters = fields[1::2] + ['']
print(''.join(v+d for v,d in zip(values, delimiters)))
if __name__ == '__main__':
split_str()
================================================
FILE: cookbook/c02/p02_str_start.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 检查字符串开始或结尾
Desc :
"""
import re
import os
from urllib.request import urlopen
def start_end():
filename = 'spam.txt'
print(filename.endswith('.txt'))
print(filename.startswith('file:'))
url = 'http://www.python.org'
print(url.startswith('http:'))
filenames = os.listdir('.')
print(filenames)
print([name for name in filenames if name.endswith(('.py', '.c'))])
print(any(name.endswith('.py') for name in filenames))
choices = ['http:', 'ftp:']
url = 'http://www.python.org'
url.startswith(tuple(choices))
# 切片实现,看上去不美
filename = 'spam.txt'
print(filename[-4:] == '.txt')
url = 'http://www.python.org'
print(url[:5] == 'http:' or url[:6] == 'https:' or url[:4] == 'ftp:')
# 正则式实现
url = 'http://www.python.org'
print(re.match('http:|https:|ftp:', url))
def read_data(name):
if name.startswith(('http:', 'https:', 'ftp:')):
return urlopen(name).read()
else:
with open(name) as f:
return f.read()
if __name__ == '__main__':
start_end()
================================================
FILE: cookbook/c02/p03_unix_match.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: Unix Shell通配符匹配
Desc :
"""
from fnmatch import fnmatch, fnmatchcase
def unix_match():
print(fnmatch('foo.txt', '*.txt'))
print(fnmatch('foo.txt', '?oo.txt'))
print(fnmatch('Dat45.csv', 'Dat[0-9]*'))
names = ['Dat1.csv', 'Dat2.csv', 'config.ini', 'foo.py']
print([name for name in names if fnmatch(name, 'Dat*.csv')])
# 完全按照模式大小写来
print(fnmatchcase('foo.txt', '*.TXT'))
# 处理普通文本
addresses = [
'5412 N CLARK ST',
'1060 W ADDISON ST',
'1039 W GRANVILLE AVE',
'2122 N CLARK ST',
'4802 N BROADWAY',
]
print([addr for addr in addresses if fnmatchcase(addr, '* ST')])
print([addr for addr in addresses if fnmatchcase(addr, '54[0-9][0-9] *CLARK*')])
if __name__ == '__main__':
unix_match()
================================================
FILE: cookbook/c02/p04_match_search.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 字符串匹配和搜索
Desc :
"""
import re
def match_search():
# 字面字符串匹配
text = 'yeah, but no, but yeah, but no, but yeah'
print(text == 'yeah')
print(text.startswith('yeah'))
print(text.endswith('no'))
print(text.find('no'))
# 简单的日期匹配
text1 = '11/27/2012'
text2 = 'Nov 27, 2012'
if re.match(r'\d+/\d+/\d+', text1):
print('yes')
else:
print('no')
if re.match(r'\d+/\d+/\d+', text2):
print('yes')
else:
print('no')
# 编译模式字符串先
datepat = re.compile(r'\d+/\d+/\d+')
if datepat.match(text1):
print('yes')
else:
print('no')
if datepat.match(text2):
print('yes')
else:
print('no')
# 使用findall()
text = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
print(datepat.findall(text))
# 括号捕获分组
datepat = re.compile(r'(\d+)/(\d+)/(\d+)')
m = datepat.match('11/27/2012')
print(m.group(0))
print(m.group(1))
print(m.group(2))
print(m.group(3))
print(m.groups())
month, day, year = m.groups()
print(datepat.findall(text))
for month, day, year in datepat.findall(text):
print('{}-{}-{}'.format(year, month, day))
# 迭代方式返回匹配
for m in datepat.finditer(text):
print(m.groups())
# 字符串整个匹配
datepat = re.compile(r'(\d+)/(\d+)/(\d+)$')
print(datepat.match('11/27/2012abcdef'))
print(datepat.match('11/27/2012'))
# 直接使用re模块级别函数
print(re.findall(r'(\d+)/(\d+)/(\d+)', text))
if __name__ == '__main__':
match_search()
================================================
FILE: cookbook/c02/p05_search_replace.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 字符串搜索和替换
Desc :
"""
import re
from calendar import month_abbr
def change_date(m):
mon_name = month_abbr[int(m.group(1))]
return '{} {} {}'.format(m.group(2), mon_name, m.group(3))
def search_replace():
text = 'yeah, but no, but yeah, but no, but yeah'
print(text.replace('yeah', 'yep'))
# 复杂的模式,使用sub()
text = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
print(re.sub(r'(\d+)/(\d+)/(\d+)', r'\3-\1-\2', text))
print(re.sub(r'(?P<month>\d+)/(?P<day>\d+)/(?P<year>\d+)', r'\g<year>-\g<month>-\g<day>', text))
# 先编译
datepat = re.compile(r'(\d+)/(\d+)/(\d+)')
print(datepat.sub(r'\3-\1-\2', text))
# 更复杂的替换,使用回调函数
print(datepat.sub(change_date, text))
# 同时返回替换次数
newtext, n = datepat.subn(r'\3-\1-\2', text)
print(newtext, n)
if __name__ == '__main__':
search_replace()
================================================
FILE: cookbook/c02/p06_case_insensitive.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 忽略大小写
Desc :
"""
import re
def matchcase(word):
def replace(m):
text = m.group()
if text.isupper():
return word.upper()
elif text.islower():
return word.lower()
elif text[0].isupper():
return word.capitalize()
else:
return word
return replace
def case_insens():
text = 'UPPER PYTHON, lower python, Mixed Python'
print(re.findall('python', text, flags=re.IGNORECASE))
print(re.sub('python', 'snake', text, flags=re.IGNORECASE))
# 大小写自动匹配
print(re.sub('python', matchcase('snake'), text, flags=re.IGNORECASE))
if __name__ == '__main__':
case_insens()
================================================
FILE: cookbook/c02/p07_shortest_match.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 最短匹配,非贪婪模式匹配
Desc :
"""
import re
def short_match():
# 贪婪模式
str_pat = re.compile(r'\"(.*)\"')
text1 = 'Computer says "no."'
print(str_pat.findall(text1))
text2 = 'Computer says "no." Phone says "yes."'
print(str_pat.findall(text2))
# 非贪婪模式
str_pat = re.compile(r'\"(.*?)\"')
print(str_pat.findall(text2))
if __name__ == '__main__':
short_match()
================================================
FILE: cookbook/c02/p08_multiline_match.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 多行匹配
Desc :
"""
import re
def multiline_match():
comment = re.compile(r'/\*(.*?)\*/')
text1 = '/* this is a comment */'
text2 = '''/* this is a
multiline comment */
'''
print(comment.findall(text1))
print(comment.findall(text2))
# 修正模式
comment = re.compile(r'/\*((?:.|\n)*?)\*/')
print(comment.findall(text2))
# 使用标志参数re.DOTALL,复杂匹配时不推荐
comment = re.compile(r'/\*(.*?)\*/', re.DOTALL)
print(comment.findall(text2))
if __name__ == '__main__':
multiline_match()
================================================
FILE: cookbook/c02/p09_normal_unicode.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: unicode字符串标准化表示
Desc :
"""
import unicodedata
def nor_unicode():
s1 = 'Spicy Jalape\u00f1o'
s2 = 'Spicy Jalapen\u0303o'
print(s1, s2)
print(s1 == s2)
print(len(s1), len(s2))
# 先将文本标准化表示
t1 = unicodedata.normalize('NFC', s1)
t2 = unicodedata.normalize('NFC', s2)
print(t1 == t2)
print(ascii(t1))
t3 = unicodedata.normalize('NFD', s1)
t4 = unicodedata.normalize('NFD', s2)
print(t3 == t4)
print(ascii(t3))
# 扩展的NFKC和NFKD
s = '\ufb01' # A single character
print(s, len(s))
print(unicodedata.normalize('NFD', s), len(unicodedata.normalize('NFD', s)))
print(unicodedata.normalize('NFKC', s), len(unicodedata.normalize('NFKC', s)))
print(unicodedata.normalize('NFKD', s), len(unicodedata.normalize('NFKD', s)))
# 消除变音符
t1 = unicodedata.normalize('NFD', s1)
print(''.join(c for c in t1 if not unicodedata.combining(c)))
if __name__ == '__main__':
nor_unicode()
================================================
FILE: cookbook/c02/p10_re_unicode.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 在正则式中使用Unicode
Desc :
"""
import re
def re_unicode():
num = re.compile('\d+')
# ASCII digits
print(num.match('123'))
# 阿拉伯数字
print(num.match('\u0661\u0662\u0663'))
# 匹配所有阿拉伯编码字符
arabic = re.compile('[\u0600-\u06ff\u0750-\u077f\u08a0-\u08ff]+')
# 大小写忽略情形
pat = re.compile('stra\u00dfe', re.IGNORECASE)
s = 'straße'
print(pat.match(s))
print(pat.match(s.upper())) # Doesn't match
print(s.upper()) # 大小写转换
if __name__ == '__main__':
re_unicode()
================================================
FILE: cookbook/c02/p11_strip.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 去除字符串中多余字符
Desc :
"""
import re
def strip_str():
s = ' hello world \n'
print(s.strip())
print(s.lstrip())
print(s.rstrip())
# Character stripping
t = '-----hello====='
print(t.lstrip('-'))
print(t.strip('-='))
# 对中间不会影响
s = ' hello world \n'
print(s.strip())
print(s.replace(' ', ''))
print(re.sub('\s+', ' ', s))
# 生成器表达式
with open('filename') as f:
lines = (line.strip() for line in f)
for line in lines:
pass
if __name__ == '__main__':
strip_str()
================================================
FILE: cookbook/c02/p12_translate.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: str的translate方法清理文本
Desc :
"""
import unicodedata
import sys
def clean_spaces(s):
"""普通替换使用replace最快"""
s = s.replace('\r', '')
s = s.replace('\t', ' ')
s = s.replace('\f', ' ')
return s
def translate_str():
s = 'pýtĥöñ\fis\tawesome\r\n'
print(s)
remap = {
ord('\t'): ' ',
ord('\f'): ' ',
ord('\r'): None # Deleted
}
a = s.translate(remap)
print(a)
# 删除和音符
cmb_chrs = dict.fromkeys(c for c in range(sys.maxunicode)
if unicodedata.combining(chr(c)))
b = unicodedata.normalize('NFD', a)
print(b)
print(b.translate(cmb_chrs))
# unicode数字字符映射到ascii字符
digitmap = {c: ord('0') + unicodedata.digit(chr(c))
for c in range(sys.maxunicode)
if unicodedata.category(chr(c)) == 'Nd'}
print(len(digitmap))
x = '\u0661\u0662\u0663'
print(x.translate(digitmap))
# 先标准化,然后使用encode和decode函数
b = unicodedata.normalize('NFD', a)
print(type(b))
print(b.encode('ascii', 'ignore').decode('ascii'))
if __name__ == '__main__':
translate_str()
================================================
FILE: cookbook/c02/p13_align_str.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 对齐字符串
Desc :
"""
def align_str():
text = 'Hello World'
print(text.ljust(20))
print(text.rjust(20))
print(text.center(20))
# 填充字符
print(text.rjust(20,'='))
print(text.center(20,'*'))
# format函数
print(format(text, '>20'))
print(format(text, '<20'))
print(format(text, '^20'))
# 同时增加填充字符
print(format(text, '=>20s'))
print(format(text, '*^20s'))
# 格式化多个值
print('{:=>10s} {:*^10s}'.format('Hello', 'World'))
# 格式化数字
x = 1.2345
print(format(x, '=^10.2f'))
if __name__ == '__main__':
align_str()
================================================
FILE: cookbook/c02/p14_join_str.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 字符串合并
Desc :
"""
def combine(source, maxsize):
parts = []
size = 0
for part in source:
parts.append(part)
size += len(part)
if size > maxsize:
yield ''.join(parts)
parts = []
size = 0
yield ''.join(parts)
def sample():
yield 'Is'
yield 'Chicago'
yield 'Not'
yield 'Chicago?'
def join_str():
parts = ['Is', 'Chicago', 'Not', 'Chicago?']
print(' '.join(parts))
print(','.join(parts))
print(''.join(parts))
# 使用+
a = 'Is Chicago'
b = 'Not Chicago?'
c = 'ccc'
print(a + ' ' + b)
data = ['ACME', 50, 91.1]
print(','.join(str(d) for d in data))
print(a + ':' + b + ':' + c) # Ugly
print(':'.join([a, b, c])) # Still ugly
print(a, b, c, sep=':') # Better
# 混合方案
# with open('filename', 'w') as f:
# for part in combine(sample(), 32768):
# f.write(part)
for part in combine(sample(), 32768):
print(part)
if __name__ == '__main__':
join_str()
================================================
FILE: cookbook/c02/p15_var_string.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 字符串中的变量
Desc :
"""
import sys
class Info:
def __init__(self, name, n):
self.name = name
self.n = n
class SafeSub(dict):
"""防止key找不到"""
def __missing__(self, key):
return '{' + key + '}'
def sub(text):
return text.format_map(SafeSub(sys._getframe(1).f_locals))
def var_str():
s = '{name} has {n} messages.'
print(s.format(name='Guido', n=37))
# vars()和format_map
a = Info('Guido', 37)
print(s.format_map(vars(a)))
name = 'Lisi'
print(s.format_map(SafeSub(vars())))
name = 'Guido'
n = 37
print(sub('Hello {name}'))
print(sub('You have {n} messages.'))
print(sub('Your favorite color is {color}'))
if __name__ == '__main__':
var_str()
================================================
FILE: cookbook/c02/p16_textwrap.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 格式化字符串为指定宽度
Desc :
"""
import textwrap
import os
def reformat_width():
s = "Look into my eyes, look into my eyes, the eyes, the eyes, \
the eyes, not around the eyes, don't look around the eyes, \
look into my eyes, you're under."
print(textwrap.fill(s, 70))
print('*' * 40)
print(textwrap.fill(s, 40))
print('*' * 40)
print(textwrap.fill(s, 40, initial_indent=' '))
print('*' * 40)
print(textwrap.fill(s, 40, subsequent_indent=' '))
# 获取终端屏幕尺寸
print(os.get_terminal_size().columns)
if __name__ == '__main__':
reformat_width()
================================================
FILE: cookbook/c02/p17_html_xml.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 处理html和xml文本
Desc :
"""
import html
def html_xml():
s = 'Elements are written as "<tag>text</tag>".'
print(s)
print(html.escape(s))
# Disable escaping of quotes
print(html.escape(s, quote=False))
s = 'Spicy Jalapeño'
print(s.encode('ascii', errors='xmlcharrefreplace'))
if __name__ == '__main__':
html_xml()
================================================
FILE: cookbook/c02/p18_tokenize.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 字符串令牌化
Desc :
"""
import re
from collections import namedtuple
def tokenize_str():
text = 'foo = 23 + 42 * 10'
tokens = [('NAME', 'foo'), ('EQ', '='), ('NUM', '23'), ('PLUS', '+'),
('NUM', '42'), ('TIMES', '*'), ('NUM', '10')]
NAME = r'(?P<NAME>[a-zA-Z_][a-zA-Z_0-9]*)'
NUM = r'(?P<NUM>\d+)'
PLUS = r'(?P<PLUS>\+)'
TIMES = r'(?P<TIMES>\*)'
EQ = r'(?P<EQ>=)'
WS = r'(?P<WS>\s+)'
master_pat = re.compile('|'.join([NAME, NUM, PLUS, TIMES, EQ, WS]))
scanner = master_pat.scanner('foo = 42')
a = scanner.match()
print(a)
print((a.lastgroup, a.group()))
a = scanner.match()
print(a)
print((a.lastgroup, a.group()))
a = scanner.match()
print(a)
print((a.lastgroup, a.group()))
a = scanner.match()
print(a)
print((a.lastgroup, a.group()))
a = scanner.match()
print(a)
print((a.lastgroup, a.group()))
a = scanner.match()
print(a)
# 实际生成器代码
# Example use
for tok in generate_tokens(master_pat, 'foo = 42'):
print(tok)
# Produces output
# Token(type='NAME', value='foo')
# Token(type='WS', value=' ')
# Token(type='EQ', value='=')
# Token(type='WS', value=' ')
# Token(type='NUM', value='42')
tokens = (tok for tok in generate_tokens(master_pat, text)
if tok.type != 'WS')
for tok in tokens:
print(tok)
print('*'*40)
LT = r'(?P<LT><)'
LE = r'(?P<LE><=)'
EQ = r'(?P<EQ>=)'
master_pat = re.compile('|'.join([LE, LT, EQ])) # Correct
# master_pat = re.compile('|'.join([LT, LE, EQ])) # Incorrect
def generate_tokens(pat, text):
Token = namedtuple('Token', ['type', 'value'])
scanner = pat.scanner(text)
for m in iter(scanner.match, None):
yield Token(m.lastgroup, m.group())
if __name__ == '__main__':
tokenize_str()
================================================
FILE: cookbook/c02/p19_descent_parser.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 下降解析器
Desc :
"""
import re
import collections
# Token specification
NUM = r'(?P<NUM>\d+)'
PLUS = r'(?P<PLUS>\+)'
MINUS = r'(?P<MINUS>-)'
TIMES = r'(?P<TIMES>\*)'
DIVIDE = r'(?P<DIVIDE>/)'
LPAREN = r'(?P<LPAREN>\()'
RPAREN = r'(?P<RPAREN>\))'
WS = r'(?P<WS>\s+)'
master_pat = re.compile('|'.join([NUM, PLUS, MINUS, TIMES,
DIVIDE, LPAREN, RPAREN, WS]))
# Tokenizer
Token = collections.namedtuple('Token', ['type', 'value'])
def generate_tokens(text):
scanner = master_pat.scanner(text)
for m in iter(scanner.match, None):
tok = Token(m.lastgroup, m.group())
if tok.type != 'WS':
yield tok
# Parser
class ExpressionEvaluator:
'''
Implementation of a recursive descent parser. Each method
implements a single grammar rule. Use the ._accept() method
to test and accept the current lookahead token. Use the ._expect()
method to exactly match and discard the next token on on the input
(or raise a SyntaxError if it doesn't match).
'''
def parse(self, text):
self.tokens = generate_tokens(text)
self.tok = None # Last symbol consumed
self.nexttok = None # Next symbol tokenized
self._advance() # Load first lookahead token
return self.expr()
def _advance(self):
'Advance one token ahead'
self.tok, self.nexttok = self.nexttok, next(self.tokens, None)
def _accept(self, toktype):
'Test and consume the next token if it matches toktype'
if self.nexttok and self.nexttok.type == toktype:
self._advance()
return True
else:
return False
def _expect(self, toktype):
'Consume next token if it matches toktype or raise SyntaxError'
if not self._accept(toktype):
raise SyntaxError('Expected ' + toktype)
# Grammar rules follow
def expr(self):
"expression ::= term { ('+'|'-') term }*"
exprval = self.term()
while self._accept('PLUS') or self._accept('MINUS'):
op = self.tok.type
right = self.term()
if op == 'PLUS':
exprval += right
elif op == 'MINUS':
exprval -= right
return exprval
def term(self):
"term ::= factor { ('*'|'/') factor }*"
termval = self.factor()
while self._accept('TIMES') or self._accept('DIVIDE'):
op = self.tok.type
right = self.factor()
if op == 'TIMES':
termval *= right
elif op == 'DIVIDE':
termval /= right
return termval
def factor(self):
"factor ::= NUM | ( expr )"
if self._accept('NUM'):
return int(self.tok.value)
elif self._accept('LPAREN'):
exprval = self.expr()
self._expect('RPAREN')
return exprval
else:
raise SyntaxError('Expected NUMBER or LPAREN')
def descent_parser():
e = ExpressionEvaluator()
print(e.parse('2'))
print(e.parse('2 + 3'))
print(e.parse('2 + 3 * 4'))
print(e.parse('2 + (3 + 4) * 5'))
# print(e.parse('2 + (3 + * 4)'))
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# File "exprparse.py", line 40, in parse
# return self.expr()
# File "exprparse.py", line 67, in expr
# right = self.term()
# File "exprparse.py", line 77, in term
# termval = self.factor()
# File "exprparse.py", line 93, in factor
# exprval = self.expr()
# File "exprparse.py", line 67, in expr
# right = self.term()
# File "exprparse.py", line 77, in term
# termval = self.factor()
# File "exprparse.py", line 97, in factor
# raise SyntaxError("Expected NUMBER or LPAREN")
# SyntaxError: Expected NUMBER or LPAREN
if __name__ == '__main__':
descent_parser()
================================================
FILE: cookbook/c02/p20_byte_str.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 字节字符串操作
Desc :
"""
import re
def byte_str():
data = b'Hello World'
print(data[0:5])
print(data.startswith(b'Hello'))
print(data.split())
print(data.replace(b'Hello', b'Hello Cruel'))
# 字节数组
data = bytearray(b'Hello World')
print(data[0:5])
print(data.startswith(b'Hello'))
print(data.split())
print(data.replace(b'Hello', b'Hello Cruel'))
# 正则式
data = b'FOO:BAR,SPAM'
print(re.split(b'[:,]',data))
# 字节字符串打印不美观
s = b'Hello World'
print(s)
print(s.decode('utf-8'))
print('{:10s} {:10d} {:10.2f}'.format ('ACME', 100, 490.1).encode('ascii'))
if __name__ == '__main__':
byte_str()
================================================
FILE: cookbook/c03/__init__.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: sample
Desc :
"""
================================================
FILE: cookbook/c03/p01_round.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 四舍五入运算
Desc :
"""
def round_num():
print(round(1.23, 1))
print(round(1.27, 1))
print(round(-1.27, 1))
print(round(1.25361,3))
# 舍入数为负数
a = 1627731
print(round(a, -1))
print(round(a, -2))
print(round(a, -3))
# 格式化输出
x = 1.23456
print(format(x, '0.2f'))
print(format(x, '0.3f'))
print('value is {:0.3f}'.format(x))
# 不要自以为是的用round去修正一些精度问题
a = 2.1
b = 4.2
c = a + b
print(c)
c = round(c, 2) # "Fix" result (???)
print(c)
if __name__ == '__main__':
round_num()
================================================
FILE: cookbook/c03/p02_accurate_decimal.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 精确的浮点数运算
Desc :
"""
from decimal import Decimal
from decimal import localcontext
import math
def acc_deciamal():
a = 4.2
b = 2.1
print(a + b)
print((a + b) == 6.3)
# 使用decimal模块
a = Decimal('4.2')
b = Decimal('2.1')
print(a + b)
print((a + b) == Decimal('6.3'))
a = Decimal('1.3')
b = Decimal('1.7')
print(a / b)
with localcontext() as ctx:
ctx.prec = 3
print(a / b)
nums = [1.23e+18, 1, -1.23e+18]
print(sum(nums))
print(math.fsum(nums))
if __name__ == '__main__':
acc_deciamal()
================================================
FILE: cookbook/c03/p03_format_number.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 格式化输出数字
Desc :
"""
def format_number():
x = 1234.56789
# Two decimal places of accuracy
print(format(x, '0.2f'))
# Right justified in 10 chars, one-digit accuracy
print(format(x, '>10.1f'))
# Left justified
print(format(x, '<10.1f'))
# Centered
print(format(x, '^10.1f'))
# Inclusion of thousands separator
print(format(x, ','))
print(format(x, '0,.1f'))
print(format(x, 'e'))
print(format(x, '0.2E'))
# strings
print('The value is {:0,.2f}'.format(x))
print(format(x, '0.1f'))
print(format(-x, '0.1f'))
swap_separators = {ord('.'): ',', ord(','): '.'}
print(format(x, ',').translate(swap_separators))
if __name__ == '__main__':
format_number()
================================================
FILE: cookbook/c03/p04_bin_octal.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 不同进制的数字表示输出
Desc :
"""
def bin_octal():
x = 1234
print(type(bin(x)))
print(bin(x), oct(x), hex(x))
# format() function
print(format(x, 'b'))
print(format(x, 'o'))
print(format(x, 'x'))
print(int('4d2', 16))
print(int('10011010010', 2))
if __name__ == '__main__':
bin_octal()
================================================
FILE: cookbook/c03/p05_int_bytes.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 大整数与字节的相互转换
Desc :
"""
def int_bytes():
data = b'\x00\x124V\x00x\x90\xab\x00\xcd\xef\x01\x00#\x004'
print(len(data))
print(int.from_bytes(data, 'little'))
print(int.from_bytes(data, 'big'))
x = 94522842520747284487117727783387188
print(x.to_bytes(16, 'big'))
print(x.to_bytes(20, 'big'))
# bit_length真有用
x = 523 ** 23
print(x)
print(x.bit_length())
nbytes, rem = divmod(x.bit_length(), 8)
if rem:
nbytes += 1
print(x.to_bytes(nbytes, 'little'))
if __name__ == '__main__':
int_bytes()
================================================
FILE: cookbook/c03/p06_complex.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: sample
Desc :
"""
import cmath
def complex_math():
a = complex(2, 4)
b = 3 - 5j
print(a.conjugate())
# 正弦 余弦 平方根等
print(cmath.sin(a))
print(cmath.cos(a))
print(cmath.sqrt(a))
if __name__ == '__main__':
complex_math()
================================================
FILE: cookbook/c03/p07_inf_nan.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 无穷大与NaN
Desc :
"""
def inf_nan():
a = float('inf')
b = float('-inf')
c = float('nan')
print(a + 45)
print(a + 45 == a)
print(a * 10 == a)
print(10 / a)
# undefined
print(a / a)
print(a + b)
print(c + 23)
print(c / 2 == c) # False ?
if __name__ == '__main__':
inf_nan()
================================================
FILE: cookbook/c03/p08_fraction.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 分数运算
Desc :
"""
from fractions import Fraction
def frac():
a = Fraction(5, 4)
b = Fraction(7, 16)
print(print(a + b))
print(a.numerator, a.denominator)
c = a + b
print(float(c))
print(type(c.limit_denominator(8)))
print(c.limit_denominator(8))
if __name__ == '__main__':
frac()
================================================
FILE: cookbook/c03/p09_array_numpy.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 利用numpy执行数组运算
Desc :
"""
import numpy as np
def array_numpy():
x = [1, 2, 3, 4]
y = [5, 6, 7, 8]
print(x * 2)
print(x + y)
# Numpy arrays
ax = np.array([1, 2, 3, 4])
ay = np.array([5, 6, 7, 8])
print(ax * 2)
print(ax + ay)
print(ax * ay)
print(f(ax))
print(np.sqrt(ax))
print(np.cos(ax))
# 大数组
grid = np.zeros(shape=(10000, 10000), dtype=float)
grid += 10
print(grid)
print(np.sin(grid))
# 二维数组的索引操作
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print(a)
print(a[1]) # Select row 1
print(a[:, 1]) # Select column 1
# Select a subregion and change it
print(a[1:3, 1:3])
a[1:3, 1:3] += 10
print(a)
# Broadcast a row vector across an operation on all rows
print(a + [100, 101, 102, 103])
# Conditional assignment on an array
print(np.where(a < 10, a, 10))
def f(x):
return 3 * x ** 2 - 2 * x + 7
if __name__ == '__main__':
array_numpy()
================================================
FILE: cookbook/c03/p10_matrix_linear.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 矩阵和线性代数
Desc :
"""
import numpy as np
import numpy.linalg
def matrix_linear():
m = np.matrix([[1,-2,3],[0,4,5],[7,8,-9]])
print(m)
# Return transpose 转置矩阵
print(m.T)
# Return inverse # 逆矩阵
print(m.I)
# Create a vector and multiply
v = np.matrix([[2],[3],[4]])
print(v)
print(m * v)
# Determinant 行列式
print(numpy.linalg.det(m))
# Eigenvalues 特征值
print(numpy.linalg.eigvals(m))
# Solve for x in m*x = v
x = numpy.linalg.solve(m, v)
print(x)
print(m * x)
print(v)
if __name__ == '__main__':
matrix_linear()
================================================
FILE: cookbook/c03/p11_random_num.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 随机数
Desc :
"""
import random
def random_num():
values = [1, 2, 3, 4, 5, 6]
print(random.choice(values))
print(random.choice(values))
print(random.choice(values))
print(random.choice(values))
print(random.choice(values))
# 抽取样本
print(random.sample(values, 2))
print(random.sample(values, 2))
print(random.sample(values, 3))
# 打算顺序
random.shuffle(values)
print(values)
# 随机整数
print(random.randint(0,10))
print(random.randint(0,10))
print(random.randint(0,10))
print(random.randint(0,10))
# 随机二进制数的整数返回
print(random.getrandbits(200))
# 修改随机数生成的种子
random.seed() # Seed based on system time or os.urandom()
random.seed(12345) # Seed based on integer given
random.seed(b'bytedata') # Seed based on byte data
if __name__ == '__main__':
random_num()
================================================
FILE: cookbook/c03/p12_datatime.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 日期时间转换
Desc :
"""
from datetime import timedelta
from datetime import datetime
from dateutil.relativedelta import relativedelta
def date_time():
a = timedelta(days=2, hours=6)
b = timedelta(hours=4.5)
c = a + b
print(c.days)
print(c.seconds)
print(c.seconds / 3600)
print(c.total_seconds() / 3600)
# 具体的日期
a = datetime(2012, 9, 23)
print(a + timedelta(days=10))
b = datetime(2012, 12, 21)
d = b - a
print(d.days)
now = datetime.today()
print(now)
print(now + timedelta(minutes=10))
# 标准库中datetime模块
a = datetime(2012, 9, 23)
# a + timedelta(months=1) # 这个会报错
# 使用dateutil模块解决这个问题
print(a + relativedelta(months=+1))
print(a + relativedelta(months=+4))
# Time between two dates
b = datetime(2012, 12, 21)
d = b - a
print(d)
d = relativedelta(b, a)
print(d)
print(d.months, d.days)
if __name__ == '__main__':
date_time()
================================================
FILE: cookbook/c03/p13_last_friday.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 最后的周五
Desc :
"""
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from dateutil.rrule import *
weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday',
'Friday', 'Saturday', 'Sunday']
def get_previous_byday(dayname, start_date=None):
if start_date is None:
start_date = datetime.today()
day_num = start_date.weekday()
day_num_target = weekdays.index(dayname)
days_ago = (7 + day_num - day_num_target) % 7
if days_ago == 0:
days_ago = 7
target_date = start_date - timedelta(days=days_ago)
return target_date
def last_friday():
print(datetime.today())
print(get_previous_byday('Monday'))
print(get_previous_byday('Tuesday'))
print(get_previous_byday('Friday'))
print(get_previous_byday('Saturday'))
# 显式的传递开始日期
print(get_previous_byday('Sunday', datetime(2012, 12, 21)))
# 使用dateutil模块
d = datetime.now()
# 下一个周五
print(d + relativedelta(weekday=FR))
# 上一个周五
print(d + relativedelta(weekday=FR(-1)))
# 下一个周六, 为什么如果今天是周六,下一个/上一个都返回今天的日期??
print(d + relativedelta(weekday=SA))
# 上一个周六
print(d + relativedelta(weekday=SA(-1)))
if __name__ == '__main__':
last_friday()
================================================
FILE: cookbook/c03/p14_month_range.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 计算当前月份的日期范围
Desc :
"""
from datetime import datetime, date, timedelta
import calendar
def get_month_range(start_date=None):
if start_date is None:
start_date = date.today().replace(day=1)
_, days_in_month = calendar.monthrange(start_date.year, start_date.month)
end_date = start_date + timedelta(days=days_in_month)
return (start_date, end_date)
def date_range(start, stop, step):
while start < stop:
yield start
start += step
def month_range():
a_day = timedelta(days=1)
first_day, last_day = get_month_range()
while first_day < last_day:
print(first_day)
first_day += a_day
# 使用生成器
for d in date_range(datetime(2012, 9, 1), datetime(2012, 10, 1),
timedelta(hours=6)):
print(d)
if __name__ == '__main__':
month_range()
================================================
FILE: cookbook/c03/p15_str_datetime.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 字符串转换为datetime
Desc :
"""
from datetime import datetime
def str_datetime():
text = '2012-09-20'
y = datetime.strptime(text, '%Y-%m-%d')
z = datetime.now()
diff = z - y
print(diff)
print(z)
nice_z = datetime.strftime(z, '%A %B %d, %Y')
print(nice_z)
def parse_ymd(s):
'''自定义解析,要快很多'''
year_s, mon_s, day_s = s.split('-')
return datetime(int(year_s), int(mon_s), int(day_s))
if __name__ == '__main__':
str_datetime()
================================================
FILE: cookbook/c03/p16_timezone.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 日期时区和本地化
Desc :
"""
from datetime import datetime, timedelta
from pytz import timezone
import pytz
def tz_local():
d = datetime(2012, 12, 21, 9, 30, 0)
print(d)
# Localize the date for Chicago
central = timezone('US/Central')
loc_d = central.localize(d)
print(loc_d)
# Convert to Bangalore time
bang_d = loc_d.astimezone(timezone('Asia/Kolkata'))
print(bang_d)
# 夏令时
d = datetime(2013, 3, 10, 1, 45)
loc_d = central.localize(d)
print(loc_d)
later = loc_d + timedelta(minutes=30)
print(later)
# 使用normalize修正这个问题
later = central.normalize(loc_d + timedelta(minutes=30))
print(later)
# 一个普遍策略是先转换为UTC时间,使用UTC时间来进行计算
print(loc_d)
utc_d = loc_d.astimezone(pytz.utc)
print(utc_d)
later_utc = utc_d + timedelta(minutes=30)
# 转回到本地时间
print(later_utc.astimezone(central))
# 根据ISO 3166国家代码查找时区名称
print(pytz.country_timezones['IN'])
if __name__ == '__main__':
tz_local()
================================================
FILE: cookbook/c04/__init__.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: sample
Desc :
"""
================================================
FILE: cookbook/c04/p01_manual_iterator.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 手动遍历迭代器
Desc :
"""
def manual_iter():
with open('/etc/passwd') as f:
try:
while True:
line = next(f)
print(line, end='')
except StopIteration:
pass
def manual_iter2():
with open('/etc/passwd') as f:
while True:
line = next(f)
if line is None:
break
print(line, end='')
if __name__ == '__main__':
manual_iter()
================================================
FILE: cookbook/c04/p02_delegate_iter.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 代理迭代
Desc :
"""
class Node:
def __init__(self, value):
self._value = value
self._children = []
def __repr__(self):
return 'Node({!r})'.format(self._value)
def add_child(self, node):
self._children.append(node)
def __iter__(self):
return iter(self._children)
# Example
if __name__ == '__main__':
root = Node(0)
child1 = Node(1)
child2 = Node(2)
root.add_child(child1)
root.add_child(child2)
# Outputs Node(1), Node(2)
for ch in root:
print(ch)
================================================
FILE: cookbook/c04/p03_generator_pattern.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 使用生成器创建新的迭代模式
Desc :
"""
def frange(start, stop, increment):
x = start
while x < stop:
yield x
x += increment
def countdown(n):
print('Starting to count from', n)
while n > 0:
yield n
n -= 1
print('Done')
def gen_pattern():
for n in frange(0, 4, 0.5):
print(n)
print(list(frange(0, 1, 0.125)))
#生成器函数
# Create the generator, notice no output appears
c = countdown(3)
print(next(c))
print(next(c))
print(next(c))
print(next(c))
if __name__ == '__main__':
gen_pattern()
================================================
FILE: cookbook/c04/p04_iterator_protocol.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 自定义迭代器协议
Desc :
"""
class Node:
def __init__(self, value):
self._value = value
self._children = []
def __repr__(self):
return 'Node({!r})'.format(self._value)
def add_child(self, node):
self._children.append(node)
def __iter__(self):
return iter(self._children)
def depth_first(self):
yield self
for c in self:
yield from c.depth_first()
class Node2:
def __init__(self, value):
self._value = value
self._children = []
def __repr__(self):
return 'Node({!r})'.format(self._value)
def add_child(self, node):
self._children.append(node)
def __iter__(self):
return iter(self._children)
def depth_first(self):
return DepthFirstIterator(self)
class DepthFirstIterator(object):
'''
Depth-first traversal
'''
def __init__(self, start_node):
self._node = start_node
self._children_iter = None
self._child_iter = None
def __iter__(self):
return self
def __next__(self):
# Return myself if just started; create an iterator for children
if self._children_iter is None:
self._children_iter = iter(self._node)
return self._node
# If processing a child, return its next item
elif self._child_iter:
try:
nextchild = next(self._child_iter)
return nextchild
except StopIteration:
self._child_iter = None
return next(self)
# Advance to the next child and start its iteration
else:
self._child_iter = next(self._children_iter).depth_first()
return next(self)
# Example
if __name__ == '__main__':
root = Node(0)
child1 = Node(1)
child2 = Node(2)
root.add_child(child1)
root.add_child(child2)
child1.add_child(Node(3))
child1.add_child(Node(4))
child2.add_child(Node(5))
for ch in root.depth_first():
print(ch)
# Outputs Node(0), Node(1), Node(3), Node(4), Node(2), Node(5)
================================================
FILE: cookbook/c04/p05_reverse_iterate.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 方向迭代
Desc :
"""
def reverse_iterate():
a = [1, 2, 3, 4]
for x in reversed(a):
print(x)
# 两个条件:大小可知或者实现__reversed__方法,
# 如果都不满足,先转换为list
# Print a file backwards
# f = open('somefile')
# for line in reversed(list(f)):
# print(line, end='')
for rr in reversed(Countdown(30)):
print(rr)
for rr in Countdown(30):
print(rr)
class Countdown:
def __init__(self, start):
self.start = start
# Forward iterator
def __iter__(self):
n = self.start
while n > 0:
yield n
n -= 1
# Reverse iterator
def __reversed__(self):
n = 1
while n <= self.start:
yield n
n += 1
if __name__ == '__main__':
reverse_iterate()
================================================
FILE: cookbook/c04/p06_generator_extrastate.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 带外部状态的生成器
Desc :
"""
from collections import deque
class linehistory:
def __init__(self, lines, histlen=3):
self.lines = lines
self.history = deque(maxlen=histlen)
def __iter__(self):
for lineno, line in enumerate(self.lines, 1):
self.history.append((lineno, line))
yield line
def clear(self):
self.history.clear()
def gen_extrastate():
with open('somefile.txt') as f:
lines = linehistory(f)
for line in lines:
if 'python' in line:
for lineno, hline in lines.history:
print('{}:{}'.format(lineno, hline), end='')
if __name__ == '__main__':
gen_extrastate()
================================================
FILE: cookbook/c04/p07_iterator_slice.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 迭代器和生成器切片
Desc :
"""
import itertools
def count(n):
while True:
yield n
n += 1
def iter_slice():
c = count(0)
for x in itertools.islice(c, 10, 20):
print(x)
if __name__ == '__main__':
iter_slice()
================================================
FILE: cookbook/c04/p08_skip_iterable.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 跳过可迭代对象开始部分
Desc :
"""
from itertools import dropwhile
from itertools import islice
def skip_iter():
# with open('/etc/passwd') as f:
# for line in dropwhile(lambda line: not line.startswith('#'), f):
# print(line, end='')
# 明确知道了要跳过的元素序号
items = ['a', 'b', 'c', 1, 4, 10, 15]
for x in islice(items, 3, None):
print(x)
if __name__ == '__main__':
skip_iter()
================================================
FILE: cookbook/c04/p09_iter_permutation.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 排列组合迭代
Desc :
"""
from itertools import permutations
from itertools import combinations
from itertools import combinations_with_replacement
def iter_permutation():
"""排列组合"""
items = ['a', 'b', 'c']
# 全排列
for p in permutations(items):
print(p)
# 指定长度
for p in permutations(items, 2):
print(p)
# 组合
for c in combinations(items, 3):
print(c)
# 可重复组合
for c in combinations_with_replacement(items, 3):
print(c)
if __name__ == '__main__':
iter_permutation()
================================================
FILE: cookbook/c04/p10_iterate_index.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 迭代并跟踪索引
Desc :
"""
from collections import defaultdict
def iterate_index():
my_list = ['a', 'b', 'c']
for idx, val in enumerate(my_list):
print(idx, val)
# 索引从1开始
for idx, val in enumerate(my_list, 1):
print(idx, val)
# 序列中含有元组的解压
data = [ (1, 2), (3, 4), (5, 6), (7, 8) ]
for n, (x, y) in enumerate(data):
print(n)
print(x, y)
def parse_data(filename):
with open(filename, 'rt') as f:
for lineno, line in enumerate(f, 1):
fields = line.split()
try:
count = int(fields[1])
# ...
except ValueError as e:
print('Line {}: Parse error: {}'.format(lineno, e))
def word_lines():
word_summary = defaultdict(list)
with open('myfile.txt', 'r') as f:
lines = f.readlines()
for idx, line in enumerate(lines):
# Create a list of words in current line
words = [w.strip().lower() for w in line.split()]
for word in words:
word_summary[word].append(idx)
if __name__ == '__main__':
iterate_index()
================================================
FILE: cookbook/c04/p11_iterate_simultaneous.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 同时迭代多个序列
Desc :
"""
from itertools import zip_longest
def iterate_simul():
xpts = [1, 5, 4, 2, 10, 7]
ypts = [101, 78, 37, 15, 62, 99]
for x, y in zip(xpts, ypts):
print(x, y)
a = [1, 2, 3]
b = ['w', 'x', 'y', 'z']
for i in zip(a,b):
print(i) # 默认是按最短长度
for i in zip_longest(a,b):
print(i)
for i in zip_longest(a, b, fillvalue=0):
print(i)
headers = ['name', 'shares', 'price']
values = ['ACME', 100, 490.1]
s = dict(zip(headers,values))
for name, val in zip(headers, values):
print(name, '=', val)
if __name__ == '__main__':
iterate_simul()
================================================
FILE: cookbook/c04/p12_iterate_separate.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 在不同容器中迭代
Desc :
"""
from itertools import chain
def iter_separate():
a = [1, 2, 3, 4]
b = ['x', 'y', 'z']
for x in chain(a, b):
print(x)
if __name__ == '__main__':
iter_separate()
================================================
FILE: cookbook/c04/p13_process_pipline.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: sample
Desc :
"""
import os
import fnmatch
import gzip
import bz2
import re
def gen_find(filepat, top):
'''
Find all filenames in a directory tree that match a shell wildcard pattern
'''
for path, dirlist, filelist in os.walk(top):
for name in fnmatch.filter(filelist, filepat):
yield os.path.join(path, name)
def gen_opener(filenames):
'''
Open a sequence of filenames one at a time producing a file object.
The file is closed immediately when proceeding to the next iteration.
'''
for filename in filenames:
if filename.endswith('.gz'):
f = gzip.open(filename, 'rt')
elif filename.endswith('.bz2'):
f = bz2.open(filename, 'rt')
else:
f = open(filename, 'rt')
yield f
f.close()
def gen_concatenate(iterators):
'''
Chain a sequence of iterators together into a single sequence.
'''
for it in iterators:
yield from it
def gen_grep(pattern, lines):
'''
Look for a regex pattern in a sequence of lines
'''
pat = re.compile(pattern)
for line in lines:
if pat.search(line):
yield line
def process_pipline():
lognames = gen_find('access-log*', 'www')
files = gen_opener(lognames)
lines = gen_concatenate(files)
pylines = gen_grep('(?i)python', lines)
for line in pylines:
print(line)
lognames = gen_find('access-log*', 'www')
files = gen_opener(lognames)
lines = gen_concatenate(files)
pylines = gen_grep('(?i)python', lines)
bytecolumn = (line.rsplit(None, 1)[1] for line in pylines)
bytes = (int(x) for x in bytecolumn if x != '-')
print('Total', sum(bytes))
if __name__ == '__main__':
process_pipline()
================================================
FILE: cookbook/c04/p14_flatten_sequence.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: sample
Desc :
"""
from collections import Iterable
def flatten(items, ignore_types=(str, bytes)):
for x in items:
if isinstance(x, Iterable) and not isinstance(x, ignore_types):
yield from flatten(x)
else:
yield x
def flatten_seq():
items = [1, 2, [3, 4, [5, 6], 7], 8]
# Produces 1 2 3 4 5 6 7 8
for x in flatten(items):
print(x)
items = ['Dave', 'Paula', ['Thomas', 'Lewis']]
for x in flatten(items):
print(x)
if __name__ == '__main__':
flatten_seq()
================================================
FILE: cookbook/c04/p15_merge_sorted.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: sample
Desc :
"""
import heapq
def merge_sorted():
a = [1, 4, 7, 10]
b = [2, 5, 6, 11]
for c in heapq.merge(a, b):
print(c)
# 合并排序文件
with open('sorted_file_1', 'rt') as file1, \
open('sorted_file_2', 'rt') as file2, \
open('merged_file', 'wt') as outf:
for line in heapq.merge(file1, file2):
outf.write(line)
if __name__ == '__main__':
merge_sorted()
================================================
FILE: cookbook/c04/p16_iterate_while.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 使用迭代器重写while无限循环
Desc :
"""
import sys
def process_data():
print(data)
def reader(s, size):
while True:
data = s.recv(size)
if data == b'':
break
# process_data(data)
def reader2(s, size):
for data in iter(lambda: s.recv(size), b''):
process_data(data)
def iterate_while():
CHUNKSIZE = 8192
with open('/etc/passwd') as f:
for chunk in iter(lambda: f.read(10), ''):
n = sys.stdout.write(chunk)
if __name__ == '__main__':
iterate_while()
================================================
FILE: cookbook/c05/__init__.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: sample
Desc :
"""
================================================
FILE: cookbook/c05/p01_rw_text.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 读写文本文件
Desc :
"""
def rw_text():
# Iterate over the lines of the file
with open('somefile.txt', 'rt') as f:
for line in f:
# process line
print(line)
# Write chunks of text data
with open('somefile.txt', 'wt') as f:
f.write('text1')
f.write('text2')
if __name__ == '__main__':
rw_text()
================================================
FILE: cookbook/c05/p02_print_tofile.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 输出重定向到文件
Desc :
"""
def print_tofile():
with open('d:/work/test.txt', 'wt') as f:
print('Hello World!', file=f)
if __name__ == '__main__':
print_tofile()
================================================
FILE: cookbook/c05/p03_print_sepend.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: print分隔符和结尾符
Desc :
"""
def print_sepend():
print('ACME', 50, 91.5)
print('ACME', 50, 91.5, sep=',')
print('ACME', 50, 91.5, sep=',', end='!!\n')
for i in range(5):
print(i)
for i in range(5):
print(i, end=' ')
print()
row = ['ACME', 50, 91.5]
print(*row, sep=',')
if __name__ == '__main__':
print_sepend()
================================================
FILE: cookbook/c05/p04_rw_binary.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 读写二进制文件
Desc :
"""
def rw_binary():
# Read the entire file as a single byte string
with open('somefile.bin', 'rb') as f:
data = f.read()
# Write binary data to a file
with open('somefile.bin', 'wb') as f:
f.write(b'Hello World')
# Text string
t = 'Hello World'
print(t[0])
# Byte string
b = b'Hello World'
print(b[0])
for c in b:
print(c)
if __name__ == '__main__':
rw_binary()
================================================
FILE: cookbook/c05/p05_write_notexist.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 文件不存在时才写入
Desc :
"""
def write_noexist():
with open('D:/work/test1.txt', 'wt') as f:
f.write('BBBBBBBBBBBB')
with open('D:/work/tt.txt', 'xt') as f:
f.write('XXXXXXX')
if __name__ == '__main__':
write_noexist()
================================================
FILE: cookbook/c05/p06_string_io.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 字符串的I/O操作
Desc :
"""
import io
def string_io():
s = io.StringIO()
s.write('Hello World\n')
print('This is a test', file=s)
# Get all of the data written so far
print(s.getvalue())
# Wrap a file interface around an existing string
s = io.StringIO('Hello\nWorld\n')
print(s.read(4))
print(s.read())
if __name__ == '__main__':
string_io()
================================================
FILE: cookbook/c05/p07_gzip_bz2.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 读写压缩文件
Desc :
"""
import gzip
import bz2
def gzip_bz2():
with gzip.open('somefile.gz', 'rt') as f:
text = f.read()
with bz2.open('somefile.bz2', 'rt') as f:
text = f.read()
with gzip.open('somefile.gz', 'wt') as f:
f.write(text)
with bz2.open('somefile.bz2', 'wt') as f:
f.write(text)
with gzip.open('somefile.gz', 'wt', compresslevel=5) as f:
f.write(text)
# 作用在已打开的二进制文件上
f = open('somefile.gz', 'rb')
with gzip.open(f, 'rt') as g:
text = g.read()
if __name__ == '__main__':
gzip_bz2()
================================================
FILE: cookbook/c05/p08_iterate_fixedsize.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 固定长度迭代文件
Desc :
"""
from functools import partial
def iterate_fixed():
RECORD_SIZE = 32
with open('somefile.data', 'rb') as f:
records = iter(partial(f.read, RECORD_SIZE), b'')
for r in records:
print(r)
if __name__ == '__main__':
iterate_fixed()
================================================
FILE: cookbook/c05/p09_read_tobuffer.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 读取二进制数据到可变缓冲区中
Desc :
"""
import os.path
def read_into_buffer(filename):
buf = bytearray(os.path.getsize(filename))
with open(filename, 'rb') as f:
f.readinto(buf)
return buf
def read_tobuffer():
buf = bytearray(os.path.getsize('filename'))
print(buf)
m1 = memoryview(buf)
m2 = m1[-5:]
print(m2)
m2[:] = b'WORLD'
print(buf)
bytearray(b'Hello World')
if __name__ == '__main__':
read_tobuffer()
================================================
FILE: cookbook/c05/p10_memery_mapping.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 文件的内存映射
Desc :
"""
import os
import mmap
def memory_map(filename, access=mmap.ACCESS_WRITE):
size = os.path.getsize(filename)
fd = os.open(filename, os.O_RDWR)
return mmap.mmap(fd, size, access=access)
def mem_mapping():
pass
if __name__ == '__main__':
mem_mapping()
================================================
FILE: cookbook/c05/p11_pathnames.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 操作路径名
Desc :
"""
import os
def path_names():
path = '/Users/beazley/Data/data.csv'
print(os.path.basename(path))
print(os.path.dirname(path))
print(os.path.join('tmp', 'data', os.path.basename(path)))
path = '~/Data/data.csv'
print(os.path.expanduser(path))
print(os.path.splitext(path))
if __name__ == '__main__':
path_names()
================================================
FILE: cookbook/c05/p12_file_existence.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 测试文件或目录是否存在
Desc :
"""
import os
import time
def file_existence():
print(os.path.exists('/etc/passwd'))
print(os.path.exists('/tmp/spam'))
print(os.path.isfile('/etc/passwd'))
print(os.path.isdir('/etc/passwd'))
print(os.path.islink('/usr/local/bin/python3'))
print(os.path.realpath('/usr/local/bin/python3'))
print(os.path.getsize('/etc/passwd'))
print(os.path.getmtime('/etc/passwd'))
print(time.ctime(os.path.getmtime('/etc/passwd')))
if __name__ == '__main__':
file_existence()
================================================
FILE: cookbook/c05/p13_dir_listfile.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 目录文件列表
Desc :
"""
import os
import os.path
import glob
from fnmatch import fnmatch
def dir_listfile():
names = os.listdir('somedir')
# Get all regular files
names = [name for name in os.listdir('somedir')
if os.path.isfile(os.path.join('somedir', name))]
# Get all dirs
dirnames = [name for name in os.listdir('somedir')
if os.path.isdir(os.path.join('somedir', name))]
pyfiles = [name for name in os.listdir('somedir')
if name.endswith('.py')]
pyfiles = glob.glob('somedir/*.py')
pyfiles = [name for name in os.listdir('somedir')
if fnmatch(name, '*.py')]
pyfiles = glob.glob('*.py')
# Get file sizes and modification dates
name_sz_date = [(name, os.path.getsize(name), os.path.getmtime(name))
for name in pyfiles]
for name, size, mtime in name_sz_date:
print(name, size, mtime)
# Alternative: Get file metadata
file_metadata = [(name, os.stat(name)) for name in pyfiles]
for name, meta in file_metadata:
print(name, meta.st_size, meta.st_mtime)
if __name__ == '__main__':
dir_listfile()
================================================
FILE: cookbook/c05/p14_bypass_encode.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 忽略文件名编码
Desc :
"""
import sys
def bypass_encoding():
print(sys.getfilesystemencoding())
if __name__ == '__main__':
bypass_encoding()
================================================
FILE: cookbook/c05/p15_print_badfile.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 打印不合法文件名
Desc :
"""
import os
import sys
def bad_filename(filename):
return repr(filename)[1:-1]
def bad_filename2(filename):
"""完美方案"""
temp = filename.encode(sys.getfilesystemencoding(), errors='surrogateescape')
return temp.decode('latin-1')
def print_badfile(filename):
try:
print(filename)
except UnicodeEncodeError:
print('UnicodeEncodeError')
print(bad_filename(filename))
files = os.listdir('.')
print(files)
if __name__ == '__main__':
print_badfile('bäd.txt')
================================================
FILE: cookbook/c05/p16_change_opencode.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 增加/修改已打开文件的编码
Desc :
"""
import urllib.request
import io
import sys
def change_open_encode():
u = urllib.request.urlopen('http://www.python.org')
f = io.TextIOWrapper(u, encoding='utf-8')
text = f.read()
print(sys.stdout.encoding)
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding='latin-1')
print(sys.stdout.encoding)
f = open('sample.txt','w')
print(f)
print(f.buffer)
print(f.buffer.raw)
if __name__ == '__main__':
change_open_encode()
================================================
FILE: cookbook/c05/p17_bytes_tofile.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 在文本模式文件中写入字节
Desc :
"""
import sys
def bytes_tofile():
sys.stdout.buffer.write(b'Hello\n')
if __name__ == '__main__':
bytes_tofile()
================================================
FILE: cookbook/c05/p18_file_descriptor.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 文件描述符到文件的转换
Desc :
"""
import os
import sys
from socket import socket, AF_INET, SOCK_STREAM
def file_descriptor():
fd = os.open('somefile.txt', os.O_WRONLY | os.O_CREAT)
# Turn into a proper file
f = open(fd, 'wt')
f.write('hello world\n')
f.close()
# Create a binary-mode file for stdout
bstdout = open(sys.stdout.fileno(), 'wb', closefd=False)
bstdout.write(b'Hello World\n')
bstdout.flush()
def echo_client(client_sock, addr):
print('Got connection from', addr)
# Make text-mode file wrappers for socket reading/writing
client_in = open(client_sock.fileno(), 'rt', encoding='latin-1',
closefd=False)
client_out = open(client_sock.fileno(), 'wt', encoding='latin-1',
closefd=False)
# Echo lines back to the client using file I/O
for line in client_in:
client_out.write(line)
client_out.flush()
client_sock.close()
def echo_server(address):
sock = socket(AF_INET, SOCK_STREAM)
sock.bind(address)
sock.listen(1)
while True:
client, addr = sock.accept()
echo_client(client, addr)
if __name__ == '__main__':
file_descriptor()
================================================
FILE: cookbook/c05/p19_temp_file.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 临时文件和目录
Desc :
"""
from tempfile import TemporaryFile
from tempfile import TemporaryDirectory
from tempfile import NamedTemporaryFile
import tempfile
def temp_file():
with TemporaryFile('w+t') as f:
# Read/write to the file
f.write('Hello World\n')
f.write('Testing\n')
# Seek back to beginning and read the data
f.seek(0)
data = f.read()
print(data)
with NamedTemporaryFile('w+t') as f:
print('filename is:', f.name)
with TemporaryDirectory() as dirname:
print('dirname is:', dirname)
print(tempfile.mkstemp())
print(tempfile.mkdtemp())
print(tempfile.gettempdir())
if __name__ == '__main__':
temp_file()
================================================
FILE: cookbook/c05/p20_serial_ports.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 串行端口数据交换
Desc :
"""
import serial
def serial_posts():
ser = serial.Serial('/dev/tty.usbmodem641', # Device name varies
baudrate=9600,
bytesize=8,
parity='N',
stopbits=1)
if __name__ == '__main__':
serial_posts()
================================================
FILE: cookbook/c05/p21_serialize_object.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 序列化一个对象
Desc :
"""
import pickle
def serailize_object():
data = [1, 2, 3]
f = open('somefile', 'wb')
pickle.dump(data, f)
# 将对象转储为字符串
s = pickle.dumps(data)
# Restore from a file
f = open('somefile', 'rb')
data = pickle.load(f)
# Restore from a string
data = pickle.loads(s)
f = open('somedata', 'wb')
pickle.dump([1, 2, 3, 4], f)
pickle.dump('hello', f)
pickle.dump({'Apple', 'Pear', 'Banana'}, f)
f.close()
f = open('somedata', 'rb')
print(pickle.load(f))
print(pickle.load(f))
print(pickle.load(f))
if __name__ == '__main__':
serailize_object()
================================================
FILE: cookbook/c06/__init__.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: sample
Desc :
"""
================================================
FILE: cookbook/c06/data.json
================================================
{"name": "ACME", "shares": 100, "price": 542.23}
================================================
FILE: cookbook/c06/p01_rw_csv.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 读写CSV数据
Desc :
"""
import csv
from collections import namedtuple
def rw_csv():
with open('stocks.csv') as f:
f_csv = csv.reader(f)
headers = next(f_csv)
for row in f_csv:
print(row)
with open('stocks.csv') as f:
f_csv = csv.reader(f)
headings = next(f_csv)
Row = namedtuple('Row', headings)
for r in f_csv:
row = Row(*r)
# Process row
print(row.Change)
headers = ['Symbol', 'Price', 'Date', 'Time', 'Change', 'Volume']
rows = [('AA', 39.48, '6/11/2007', '9:36am', -0.18, 181800),
('AIG', 71.38, '6/11/2007', '9:36am', -0.15, 195500),
('AXP', 62.58, '6/11/2007', '9:36am', -0.46, 935000),
]
with open('stocks.csv', 'w') as f:
f_csv = csv.writer(f)
f_csv.writerow(headers)
f_csv.writerows(rows)
if __name__ == '__main__':
rw_csv()
================================================
FILE: cookbook/c06/p02_rw_json.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: JSON读写
Desc :
"""
import json
from collections import OrderedDict
class JSONObject:
def __init__(self, d):
self.__dict__ = d
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def serialize_instance(obj):
d = {'__classname__': type(obj).__name__}
d.update(vars(obj))
return d
def unserialize_object(d):
clsname = d.pop('__classname__', None)
if clsname:
cls = classes[clsname]
obj = cls.__new__(cls) # Make instance without calling __init__
for key, value in d.items():
setattr(obj, key, value)
return obj
else:
return d
# Dictionary mapping names to known classes
classes = {
'Point': Point
}
def rw_json():
data = {
'name': 'ACME',
'shares': 100,
'price': 542.23
}
json_str = json.dumps(data) # str类型
data = json.loads(json_str)
# Writing JSON data
with open('data.json', 'w') as f:
json.dump(data, f)
# Reading data back
with open('data.json', 'r') as f:
data = json.load(f)
# 使用object_pairs_hook
s = '{"name": "ACME", "shares": 50, "price": 490.1}'
data = json.loads(s, object_pairs_hook=OrderedDict)
print(data)
# 解码为自定义对象
# data = json.loads(s, object_hook=JSONObject)
# print(data.name)
# print(data.shares)
print(json.dumps(data))
print(json.dumps(data, indent=4))
p = Point(2, 3)
s = json.dumps(p, default=serialize_instance)
print(s)
a = json.loads(s, object_hook=unserialize_object)
print(a)
if __name__ == '__main__':
rw_json()
================================================
FILE: cookbook/c06/p03_simple_xml.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 解析简单的XML
Desc :
"""
from urllib.request import urlopen
from xml.etree.ElementTree import parse
def simple_xml():
# Download the RSS feed and parse it
u = urlopen('http://planet.python.org/rss20.xml')
doc = parse(u)
# Extract and output tags of interest
for item in doc.iterfind('channel/item'):
title = item.findtext('title')
date = item.findtext('pubDate')
link = item.findtext('link')
print(title)
print(date)
print(link)
print()
if __name__ == '__main__':
simple_xml()
================================================
FILE: cookbook/c06/p04_huge_xml.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 增量式的处理大型XML文档
Desc :
"""
from xml.etree.ElementTree import iterparse
from xml.etree.ElementTree import parse
from collections import Counter
def parse_and_remove(filename, path):
path_parts = path.split('/')
doc = iterparse(filename, ('start', 'end'))
# Skip the root element
next(doc)
tag_stack = []
elem_stack = []
for event, elem in doc:
if event == 'start':
tag_stack.append(elem.tag)
elem_stack.append(elem)
elif event == 'end':
if tag_stack == path_parts:
yield elem
elem_stack[-2].remove(elem)
try:
tag_stack.pop()
elem_stack.pop()
except IndexError:
pass
def huge_xml():
potholes_by_zip = Counter()
doc = parse('potholes.xml')
for pothole in doc.iterfind('row/row'):
potholes_by_zip[pothole.findtext('zip')] += 1
for zipcode, num in potholes_by_zip.most_common():
print(zipcode, num)
potholes_by_zip = Counter()
data = parse_and_remove('potholes.xml', 'row/row')
for pothole in data:
potholes_by_zip[pothole.findtext('zip')] += 1
for zipcode, num in potholes_by_zip.most_common():
print(zipcode, num)
if __name__ == '__main__':
huge_xml()
================================================
FILE: cookbook/c06/p05_dict_toxml.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 字典转换成XML格式
Desc :
"""
from xml.etree.ElementTree import Element
from xml.etree.ElementTree import tostring
def dict_to_xml(tag, d):
"""
Turn a simple dict of key/value pairs into XML
"""
elem = Element(tag)
for key, val in d.items():
child = Element(key)
child.text = str(val)
elem.append(child)
return elem
if __name__ == '__main__':
r = dict_to_xml('root', {'1':'22', '3':'444'})
print(r)
print(tostring(r))
r.set('_id','1234')
print(tostring(r))
================================================
FILE: cookbook/c06/p06_rw_xml.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 读取修改某个XML文档
Desc :
"""
from xml.etree.ElementTree import parse, Element
def rw_xml():
doc = parse('pred.xml')
root = doc.getroot()
# Remove a few elements
root.remove(root.find('sri'))
root.remove(root.find('cr'))
# Insert a new element after <nm>...</nm>
root.getchildren().index(root.find('nm'))
e = Element('spam')
e.text = 'This is a test'
root.insert(2, e)
# Write back to a file
doc.write('newpred.xml', xml_declaration=True)
if __name__ == '__main__':
rw_xml()
================================================
FILE: cookbook/c06/p07_namespace_xml.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 处理含命名空间的XML文档
Desc :
"""
class XMLNamespaces:
def __init__(self, **kwargs):
self.namespaces = {}
for name, uri in kwargs.items():
self.register(name, uri)
def register(self, name, uri):
self.namespaces[name] = '{' + uri + '}'
def __call__(self, path):
return path.format_map(self.namespaces)
if __name__ == '__main__':
ns = XMLNamespaces(html='http://www.w3.org/1999/xhtml')
# doc.find(ns('content/{html}html'))
# doc.findtext(ns('content/{html}html/{html}head/{html}title'))
================================================
FILE: cookbook/c06/p08_database.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 关系型数据库处理
Desc :
"""
import sqlite3
import datetime.time
def db_operation():
db = sqlite3.connect('database.db')
c = db.cursor()
c.execute('create table portfolio (symbol text, shares integer, price real)')
db.commit()
stocks = [
('GOOG', 100, 490.1),
('AAPL', 50, 545.75),
('FB', 150, 7.45),
('HPQ', 75, 33.2),
]
c.executemany('insert into portfolio values (?,?,?)', stocks)
db.commit()
for row in db.execute('select * from portfolio'):
print(row)
min_price = 12
for row in db.execute('select * from portfolio where price >= ?', (min_price,)):
print(row)
if __name__ == '__main__':
db_operation()
================================================
FILE: cookbook/c06/p09_codec_hex.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 编码/解码十六进制原始字符串
Desc :
"""
import binascii
import base64
def codec_hex():
s = b'hello'
# Encode as hex
h = binascii.b2a_hex(s)
print(h)
# Decode back to bytes
h = binascii.a2b_hex(h)
print(h)
# 使用base64模块也可以
h = base64.b16encode(s)
print(h)
print(h.decode('ascii'))
h = base64.b16decode(h)
print(h)
print(h.decode('ascii'))
if __name__ == '__main__':
codec_hex()
================================================
FILE: cookbook/c06/p10_codec_base64.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 编码/解码Base64
Desc :
"""
import base64
def codec_base64():
s = b'hello'
# Encode as Base64
a = base64.b64encode(s)
print(a)
# Decode from Base64
b = base64.b64decode(a)
print(b)
if __name__ == '__main__':
codec_base64()
================================================
FILE: cookbook/c06/p11_rw_barray.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 读写二进制数组结构的数据
Desc :
"""
from struct import Struct
from collections import namedtuple
def write_records(records, format, f):
"""
Write a sequence of tuples to a binary file of structures.
"""
record_struct = Struct(format)
for r in records:
f.write(record_struct.pack(*r))
def read_records(format, f):
record_struct = Struct(format)
chunks = iter(lambda: f.read(record_struct.size), b'')
return (record_struct.unpack(chunk) for chunk in chunks)
def unpack_records(format, data):
record_struct = Struct(format)
return (record_struct.unpack_from(data, offset)
for offset in range(0, len(data), record_struct.size))
if __name__ == '__main__':
records = [(1, 2.3, 4.5),
(6, 7.8, 9.0),
(12, 13.4, 56.7)]
with open('data.b', 'wb') as f:
write_records(records, '<idd', f)
# 增量式读取
with open('data.b','rb') as f:
for rec in read_records('<idd', f):
# Process rec
pass
# 一次性读取,再分片解析
with open('data.b', 'rb') as f:
data = f.read()
for rec in unpack_records('<idd', data):
# Process rec
pass
record_struct = Struct('<idd')
# 打印结构的字节数
print(record_struct.size)
# 打包数据
a = record_struct.pack(1, 2.0, 3.0)
print(a)
# 解包数据
print(record_struct.unpack(a))
# 解包时的命名元组
Record = namedtuple('Record', ['kind','x','y'])
with open('data.p', 'rb') as f:
records = (Record(*r) for r in read_records('<idd', f))
for r in records:
print(r.kind, r.x, r.y)
================================================
FILE: cookbook/c06/p12_var_binary.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 读写变长的二进制格式文件
Desc :
"""
import struct
import itertools
polys = [
[ (1.0, 2.5), (3.5, 4.0), (2.5, 1.5) ],
[ (7.0, 1.2), (5.1, 3.0), (0.5, 7.5), (0.8, 9.0) ],
[ (3.4, 6.3), (1.2, 0.5), (4.6, 9.2) ],
]
def write_polys(filename, polys):
# Determine bounding box
flattened = list(itertools.chain(*polys))
min_x = min(x for x, y in flattened)
max_x = max(x for x, y in flattened)
min_y = min(y for x, y in flattened)
max_y = max(y for x, y in flattened)
with open(filename, 'wb') as f:
f.write(struct.pack('<iddddi',
0x1234,
min_x, min_y,
max_x, max_y,
len(polys)))
for poly in polys:
size = len(poly) * struct.calcsize('<dd')
f.write(struct.pack('<i', size + 4))
for pt in poly:
f.write(struct.pack('<dd', *pt))
def read_polys(filename):
with open(filename, 'rb') as f:
# Read the header
header = f.read(40)
file_code, min_x, min_y, max_x, max_y, num_polys = \
struct.unpack('<iddddi', header)
polys = []
for n in range(num_polys):
pbytes, = struct.unpack('<i', f.read(4))
poly = []
for m in range(pbytes // 16):
pt = struct.unpack('<dd', f.read(16))
poly.append(pt)
polys.append(poly)
return polys
================================================
FILE: cookbook/c06/pred.xml
================================================
<?xml version="1.0"?>
<stop>
<id>14791</id>
<nm>Clark & Balmoral</nm>
<sri>
<rt>22</rt>
<d>North Bound</d>
<dd>North Bound</dd>
</sri>
<cr>22</cr>
<pre>
<pt>5 MIN</pt>
<fd>Howard</fd>
<v>1378</v>
<rn>22</rn>
</pre>
<pre>
<pt>15 MIN</pt>
<fd>Howard</fd>
<v>1867</v>
<rn>22</rn>
</pre>
</stop>
================================================
FILE: cookbook/c06/stocks.csv
================================================
Symbol,Price,Date,Time,Change,Volume
AA,39.48,6/11/2007,9:36am,-0.18,181800
AIG,71.38,6/11/2007,9:36am,-0.15,195500
AXP,62.58,6/11/2007,9:36am,-0.46,935000
================================================
FILE: cookbook/c07/__init__.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: sample
Desc :
"""
================================================
FILE: cookbook/c07/p02_keyarg_only.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 只允许关键字形式的参数
Desc :
"""
def recv(maxsize, *, block):
'Receives a message'
pass
# recv(1024, True) # TypeError
recv(1024, block=True) # Ok
def minimum(*values, clip=None):
m = min(values)
if clip is not None:
m = clip if clip > m else m
return m
minimum(1, 5, 2, -5, 10) # Returns -5
minimum(1, 5, 2, -5, 10, clip=0) # Returns 0
================================================
FILE: cookbook/c07/p03_func_annotate.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 函数注解元信息
Desc :
"""
def add(x:int, y:int) -> int:
return x + y
help(add)
print(add.__annotations__)
================================================
FILE: cookbook/c07/p05_default_argument.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 函数默认参数
Desc :
"""
def spam(a, b=42):
print(a, b)
spam(1) # Ok. a=1, b=42
spam(1, 2) # Ok. a=1, b=2
_no_value = object()
def spam(a, b=_no_value):
if b is _no_value:
print('No b value supplied')
================================================
FILE: cookbook/c07/p06_anony_func.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 匿名函数lambda表达式
Desc :
"""
add = lambda x, y: x + y
print(add(2,3))
================================================
FILE: cookbook/c07/p08_partial.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 使用partial函数来减少参数个数
Desc :
"""
import logging
from multiprocessing import Pool
from functools import partial
from socketserver import StreamRequestHandler, TCPServer
def spam(a, b, c, d):
print(a, b, c, d)
def output_result(result, log=None):
if log is not None:
log.debug('Got: %r', result)
# A sample function
def add(x, y):
return x + y
class EchoHandler(StreamRequestHandler):
# ack is added keyword-only argument. *args, **kwargs are
# any normal parameters supplied (which are passed on)
def __init__(self, *args, ack, **kwargs):
self.ack = ack
super().__init__(*args, **kwargs)
def handle(self):
for line in self.rfile:
self.wfile.write(self.ack + line)
if __name__ == '__main__':
s1 = partial(spam, 1) # a = 1
s1(2, 3, 4)
s1(4, 5, 6)
s2 = partial(spam, d=42) # d = 42
s2(1, 2, 3)
s2(4, 5, 5)
s3 = partial(spam, 1, 2, d=42) # a = 1, b = 2, d = 42
s3(3)
s3(4)
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger('test')
p = Pool()
p.apply_async(add, (3, 4), callback=partial(output_result, log=log))
p.close()
p.join()
# socket服务器
serv = TCPServer(('', 15000), partial(EchoHandler, ack=b'RECEIVED:'))
serv.serve_forever()
================================================
FILE: cookbook/c07/p09_class_to_func.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 单方法类转换为函数
Desc :
"""
from urllib.request import urlopen
class UrlTemplate:
def __init__(self, template):
self.template = template
def open(self, **kwargs):
return urlopen(self.template.format_map(kwargs))
# Example use. Download stock data from yahoo
yahoo = UrlTemplate('http://finance.yahoo.com/d/quotes.csv?s={names}&f={fields}')
for line in yahoo.open(names='IBM,AAPL,FB', fields='sl1c1v'):
print(line.decode('utf-8'))
# =======================闭包方案=================
def urltemplate(template):
def opener(**kwargs):
return urlopen(template.format_map(kwargs))
return opener
# Example use
yahoo = urltemplate('http://finance.yahoo.com/d/quotes.csv?s={names}&f={fields}')
for line in yahoo(names='IBM,AAPL,FB', fields='sl1c1v'):
print(line.decode('utf-8'))
================================================
FILE: cookbook/c07/p10_callback.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 带状态值的回调函数
Desc :
"""
def apply_async(func, args, *, callback):
# Compute the result
result = func(*args)
# Invoke the callback with the result
callback(result)
def add(x, y):
return x + y
# 类方案
class ResultHandler:
def __init__(self):
self.sequence = 0
def handler(self, result):
self.sequence += 1
print('[{}] Got: {}'.format(self.sequence, result))
r = ResultHandler()
apply_async(add, (2, 3), callback=r.handler)
apply_async(add, ('hello', 'world'), callback=r.handler)
# 闭包方案
def make_handler():
sequence = 0
def handler(result):
nonlocal sequence
sequence += 1
print('[{}] Got: {}'.format(sequence, result))
return handler
handler = make_handler()
apply_async(add, (2, 3), callback=handler)
apply_async(add, ('hello', 'world'), callback=handler)
# 协程方案
def make_handler():
sequence = 0
while True:
result = yield
sequence += 1
print('[{}] Got: {}'.format(sequence, result))
handler = make_handler()
next(handler) # Advance to the yield
apply_async(add, (2, 3), callback=handler.send)
apply_async(add, ('hello', 'world'), callback=handler.send)
================================================
FILE: cookbook/c07/p11_inline_callback.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 内联回调函数
Desc :
"""
from queue import Queue
from functools import wraps
def apply_async(func, args, *, callback):
# Compute the result
result = func(*args)
# Invoke the callback with the result
callback(result)
class Async:
def __init__(self, func, args):
self.func = func
self.args = args
def inlined_async(func):
@wraps(func)
def wrapper(*args):
f = func(*args)
result_queue = Queue()
result_queue.put(None)
while True:
print('1' * 15)
result = result_queue.get()
print('2' * 15)
try:
print('3' * 15)
print('result={}'.format(result))
a = f.send(result)
print('4' * 15)
apply_async(a.func, a.args, callback=result_queue.put)
print('5' * 15)
except StopIteration:
break
return wrapper
def add(x, y):
return x + y
@inlined_async
def test():
print('start'.center(20, '='))
r = yield Async(add, (2, 3))
print('last={}'.format(r))
r = yield Async(add, ('hello', 'world'))
print('last={}'.format(r))
# for n in range(10):
# r = yield Async(add, (n, n))
# print(r)
# print('Goodbye')
print('end'.center(20, '='))
if __name__ == '__main__':
test()
================================================
FILE: cookbook/c07/p12_closure_access.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 闭包访问函数内部变量
Desc :
"""
def sample():
n = 0
# Closure function
def func():
print('n=', n)
# Accessor methods for n
def get_n():
return n
def set_n(value):
nonlocal n
n = value
# Attach as function attributes
func.get_n = get_n
func.set_n = set_n
return func
f = sample()
f()
f.set_n(10)
f()
import sys
class ClosureInstance:
def __init__(self, locals=None):
if locals is None:
locals = sys._getframe(1).f_locals
# Update instance dictionary with callables
self.__dict__.update((key,value) for key, value in locals.items()
if callable(value) )
# Redirect special methods
def __len__(self):
return self.__dict__['__len__']()
# Example use
def Stack():
items = []
def push(item):
items.append(item)
def pop():
return items.pop()
def __len__():
return len(items)
return ClosureInstance()
s = Stack()
print(s)
s.push(10)
s.push(20)
print(len(s))
print(s.pop())
print(s.pop())
================================================
FILE: cookbook/c08/__init__.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: sample
Desc :
"""
================================================
FILE: cookbook/c08/p01_str_represent.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 实例的字符串显示
Desc :
"""
class Pair:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return 'Pair({0.x!r}, {0.y!r})'.format(self)
def __str__(self):
return '({0.x!s}, {0.y!s})'.format(self)
p = Pair(3, 4)
print(p)
================================================
FILE: cookbook/c08/p02_custom_format.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 对象自定义格式化
Desc :
"""
_formats = {
'ymd': '{d.year}-{d.month}-{d.day}',
'mdy': '{d.month}/{d.day}/{d.year}',
'dmy': '{d.day}/{d.month}/{d.year}'
}
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
def __format__(self, code):
if code == '':
code = 'ymd'
fmt = _formats[code]
return fmt.format(d=self)
d = Date(2012, 12, 21)
print(d)
print(format(d, 'mdy'))
print('The date is {:ymd}'.format(d))
print('The date is {:mdy}'.format(d))
================================================
FILE: cookbook/c08/p03_context_protocol.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 让对象支持上下文管理器
Desc :
"""
from socket import socket, AF_INET, SOCK_STREAM
class LazyConnection:
def __init__(self, address, family=AF_INET, type=SOCK_STREAM):
self.address = address
self.family = family
self.type = type
self.sock = None
def __enter__(self):
if self.sock is not None:
raise RuntimeError('Already connected')
self.sock = socket(self.family, self.type)
self.sock.connect(self.address)
return self.sock
def __exit__(self, exc_ty, exc_val, tb):
self.sock.close()
self.sock = None
from functools import partial
conn = LazyConnection(('www.python.org', 80))
# Connection closed
with conn as s:
# conn.__enter__() executes: connection open
s.send(b'GET /index.html HTTP/1.0\r\n')
s.send(b'Host: www.python.org\r\n')
s.send(b'\r\n')
resp = b''.join(iter(partial(s.recv, 8192), b''))
print(resp)
# conn.__exit__() executes: connection closed
class LazyConnection2:
def __init__(self, address, family=AF_INET, type=SOCK_STREAM):
self.address = address
self.family = family
self.type = type
self.connections = []
def __enter__(self):
sock = socket(self.family, self.type)
sock.connect(self.address)
self.connections.append(sock)
return sock
def __exit__(self, exc_ty, exc_val, tb):
self.connections.pop().close()
# Example use
from functools import partial
conn = LazyConnection2(('www.python.org', 80))
with conn as s1:
pass
with conn as s2:
pass
# s1 and s2 are independent sockets
================================================
FILE: cookbook/c08/p04_slots.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 使用slots来减少内存占用
Desc :
"""
class Date:
__slots__ = ['year', 'month', 'day']
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
================================================
FILE: cookbook/c08/p05_encapsulate_name.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 隐藏私有属性
Desc :
"""
class A:
def __init__(self):
self._internal = 0 # An internal attribute
self.public = 1 # A public attribute
def public_method(self):
'''
A public method
'''
pass
def _internal_method(self):
pass
class B:
def __init__(self):
self.__private = 0
def __private_method(self):
pass
def public_method(self):
pass
self.__private_method()
class C(B):
def __init__(self):
super().__init__()
self.__private = 1 # Does not override B.__private
# Does not override B.__private_method()
def __private_method(self):
pass
================================================
FILE: cookbook/c08/p06_managed_attribute.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 可管理的属性
Desc :
"""
import math
class Person:
def __init__(self, first_name):
self.first_name = first_name
# Getter function
@property
def first_name(self):
return self._first_name
# Setter function
@first_name.setter
def first_name(self, value):
if not isinstance(value, str):
raise TypeError('Expected a string')
self._first_name = value
# Deleter function (optional)
@first_name.deleter
def first_name(self):
raise AttributeError("Can't delete attribute")
a = Person('Guido')
print(a.first_name) # Calls the getter
# a.first_name = 42 # Calls the setter
# del a.first_name # Calls the deleter
class Person1:
def __init__(self, first_name):
self.set_first_name(first_name)
# Getter function
def get_first_name(self):
return self._first_name
# Setter function
def set_first_name(self, value):
if not isinstance(value, str):
raise TypeError('Expected a string')
self._first_name = value
# Deleter function (optional)
def del_first_name(self):
raise AttributeError("Can't delete attribute")
# Make a property from existing get/set methods
name = property(get_first_name, set_first_name, del_first_name)
print(Person1.name.fget)
print(Person1.name.fset)
print(Person1.name.fdel)
class Circle:
"""动态计算的property"""
def __init__(self, radius):
self.radius = radius
@property
def diameter(self):
return self.radius ** 2
@property
def perimeter(self):
return 2 * math.pi * self.radius
@property
def area(self):
return math.pi * self.radius ** 2
c = Circle(4.0)
print(c.radius)
print(c.area) # Notice lack of ()
================================================
FILE: cookbook/c08/p07_super_method.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: sample
Desc :
"""
class A:
def spam(self):
print('A.spam')
class B(A):
def spam(self):
print('B.spam')
super().spam() # Call parent spam()
class A1:
def __init__(self):
self.x = 0
class B1(A1):
def __init__(self):
super().__init__()
self.y = 1
class Proxy():
def __init__(self, obj):
self._obj = obj
# Delegate attribute lookup to internal obj
def __getattr__(self, name):
return getattr(self._obj, name)
# Delegate attribute assignment
def __setattr__(self, name, value):
if name.startswith('_'):
super().__setattr__(name, value) # Call original __setattr__
else:
setattr(self._obj, name, value)
class Base:
def __init__(self):
print('Base.__init__')
class AA(Base):
def __init__(self):
super().__init__()
print('AA.__init__')
class BB(Base):
def __init__(self):
super().__init__()
print('BB.__init__')
class CC(AA, BB):
def __init__(self):
super().__init__() # Only one call to super() here
print('CC.__init__')
CC()
print(CC.__mro__)
class A3:
def spam(self):
print('A3.spam')
super().spam()
class B3:
def spam(self):
print('B3.spam')
class C3(A3, B3):
pass
print(C3.__mro__)
C3().spam()
================================================
FILE: cookbook/c08/p08_extend_property.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 扩展property的功能
Desc :
"""
class Person:
def __init__(self, name):
self.name = name
# Getter function
@property
def name(self):
return self._name
# Setter function
@name.setter
def name(self, value):
if not isinstance(value, str):
raise TypeError('Expected a string')
self._name = value
# Deleter function
@name.deleter
def name(self):
raise AttributeError("Can't delete attribute")
class SubPerson(Person):
@property
def name(self):
print('Getting name')
return super().name
@name.setter
def name(self, value):
print('Setting name to', value)
super(SubPerson, SubPerson).name.__set__(self, value)
@name.deleter
def name(self):
print('Deleting name')
super(SubPerson, SubPerson).name.__delete__(self)
s = SubPerson('Guido')
print(s.name)
s.name = 'Larry'
# A descriptor
class String:
def __init__(self, name):
self.name = name
def __get__(self, instance, cls):
if instance is None:
return self
return instance.__dict__[self.name]
def __set__(self, instance, value):
if not isinstance(value, str):
raise TypeError('Expected a string')
instance.__dict__[self.name] = value
# A class with a descriptor
class Person:
name = String('name')
def __init__(self, name):
self.name = name
# Extending a descriptor with a property
class SubPerson(Person):
@property
def name(self):
print('Getting name')
return super().name
@name.setter
def name(self, value):
print('Setting name to', value)
super(SubPerson, SubPerson).name.__set__(self, value)
@name.deleter
def name(self):
print('Deleting name')
super(SubPerson, SubPerson).name.__delete__(self)
================================================
FILE: cookbook/c08/p09_descriptor.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 通过描述器定义新的实例属性
Desc :
"""
# Descriptor attribute for an integer type-checked attribute
class Integer:
def __init__(self, name):
self.name = name
def __get__(self, instance, cls):
if instance is None:
return self
else:
return instance.__dict__[self.name]
def __set__(self, instance, value):
if not isinstance(value, int):
raise TypeError('Expected an int')
instance.__dict__[self.name] = value
def __delete__(self, instance):
del instance.__dict__[self.name]
class Point:
x = Integer('x')
y = Integer('y')
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(2, 3)
print(p.x)
p.y = 5
# Descriptor for a type-checked attribute
class Typed:
def __init__(self, name, expected_type):
self.name = name
self.expected_type = expected_type
def __get__(self, instance, cls):
if instance is None:
return self
else:
return instance.__dict__[self.name]
def __set__(self, instance, value):
if not isinstance(value, self.expected_type):
raise TypeError('Expected ' + str(self.expected_type))
instance.__dict__[self.name] = value
def __delete__(self, instance):
del instance.__dict__[self.name]
# Class decorator that applies it to selected attributes
def typeassert(**kwargs):
def decorate(cls):
for name, expected_type in kwargs.items():
# Attach a Typed descriptor to the class
setattr(cls, name, Typed(name, expected_type))
return cls
return decorate
# Example use
@typeassert(name=str, shares=int, price=float)
class Stock:
def __init__(self, name, shares, price):
self.name = name
self.shares = shares
self.price = price
================================================
FILE: cookbook/c08/p10_lazy_property.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 延迟属性
Desc :
"""
import math
class lazyproperty:
def __init__(self, func):
self.func = func
def __get__(self, instance, cls):
if instance is None:
return self
else:
value = self.func(instance)
setattr(instance, self.func.__name__, value)
return value
class Circle:
def __init__(self, radius):
self.radius = radius
@lazyproperty
def area(self):
print('Computing area')
return math.pi * self.radius ** 2
@lazyproperty
def perimeter(self):
print('Computing perimeter')
return 2 * math.pi * self.radius
c = Circle(4.0)
print(vars(c))
print(c.area)
print(vars(c))
del c.area
print(vars(c))
print(c.area)
def lazyproperty2(func):
name = '_lazy_' + func.__name__
@property
def lazy(self):
if hasattr(self, name):
return getattr(self, name)
else:
value = func(self)
setattr(self, name, value)
return value
return lazy
================================================
FILE: cookbook/c08/p11_simplify_init.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 简化数据结构的初始化
Desc :
"""
import math
class Structure1:
# Class variable that specifies expected fields
_fields = []
def __init__(self, *args):
if len(args) != len(self._fields):
raise TypeError('Expected {} arguments'.format(len(self._fields)))
# Set the arguments
for name, value in zip(self._fields, args):
setattr(self, name, value)
# Example class definitions
if __name__ == '__main__':
class Stock(Structure1):
_fields = ['name', 'shares', 'price']
class Point(Structure1):
_fields = ['x', 'y']
class Circle(Structure1):
_fields = ['radius']
def area(self):
return math.pi * self.radius ** 2
s = Stock('ACME', 50, 91.1)
p = Point(2, 3)
c = Circle(4.5)
class Structure2:
_fields = []
def __init__(self, *args, **kwargs):
if len(args) > len(self._fields):
raise TypeError('Expected {} arguments'.format(len(self._fields)))
# Set all of the positional arguments
for name, value in zip(self._fields, args):
setattr(self, name, value)
# Set the remaining keyword arguments
for name in self._fields[len(args):]:
setattr(self, name, kwargs.pop(name))
# Check for any remaining unknown arguments
if kwargs:
raise TypeError('Invalid argument(s): {}'.format(','.join(kwargs)))
# Example use
if __name__ == '__main__':
class Stock(Structure2):
_fields = ['name', 'shares', 'price']
s1 = Stock('ACME', 50, 91.1)
s2 = Stock('ACME', 50, price=91.1)
s3 = Stock('ACME', shares=50, price=91.1)
# s3 = Stock('ACME', shares=50, price=91.1, aa=1)
class Structure3:
# Class variable that specifies expected fields
_fields = []
def __init__(self, *args, **kwargs):
if len(args) != len(self._fields):
raise TypeError('Expected {} arguments'.format(len(self._fields)))
# Set the arguments
for name, value in zip(self._fields, args):
setattr(self, name, value)
# Set the additional arguments (if any)
extra_args = kwargs.keys() - self._fields
for name in extra_args:
setattr(self, name, kwargs.pop(name))
if kwargs:
raise TypeError('Duplicate values for {}'.format(','.join(kwargs)))
# Example use
if __name__ == '__main__':
class Stock(Structure3):
_fields = ['name', 'shares', 'price']
s1 = Stock('ACME', 50, 91.1)
s2 = Stock('ACME', 50, 91.1, date='8/2/2012')
class Structure4:
# Class variable that specifies expected fields
_fields= []
def __init__(self, *args):
if len(args) != len(self._fields):
raise TypeError('Expected {} arguments'.format(len(self._fields)))
# Set the arguments (alternate)
self.__dict__.update(zip(self._fields,args))
================================================
FILE: cookbook/c08/p12_abstract_interface.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 定义接口或抽象类
Desc :
"""
from abc import ABCMeta, abstractmethod
class IStream(metaclass=ABCMeta):
@abstractmethod
def read(self, maxbytes=-1):
pass
@abstractmethod
def write(self, data):
pass
class SocketStream(IStream):
def read(self, maxbytes=-1):
pass
def write(self, data):
pass
class A(metaclass=ABCMeta):
@property
@abstractmethod
def name(self):
pass
@name.setter
@abstractmethod
def name(self, value):
pass
@classmethod
@abstractmethod
def method1(cls):
pass
@staticmethod
@abstractmethod
def method2():
pass
================================================
FILE: cookbook/c08/p13_type_system.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 类型检查系统
Desc :
"""
# Base class. Uses a descriptor to set a value
class Descriptor:
def __init__(self, name=None, **opts):
self.name = name
for key, value in opts.items():
setattr(self, key, value)
def __set__(self, instance, value):
instance.__dict__[self.name] = value
# Descriptor for enforcing types
class Typed(Descriptor):
expected_type = type(None)
def __set__(self, instance, value):
if not isinstance(value, self.expected_type):
raise TypeError('expected ' + str(self.expected_type))
super().__set__(instance, value)
# Descriptor for enforcing values
class Unsigned(Descriptor):
def __set__(self, instance, value):
if value < 0:
raise ValueError('Expected >= 0')
super().__set__(instance, value)
class MaxSized(Descriptor):
def __init__(self, name=None, **opts):
if 'size' not in opts:
raise TypeError('missing size option')
super().__init__(name, **opts)
def __set__(self, instance, value):
if len(value) >= self.size:
raise ValueError('size must be < ' + str(self.size))
super().__set__(instance, value)
if __name__ == '__main__':
class Integer(Typed):
expected_type = int
class UnsignedInteger(Integer, Unsigned):
pass
class Float(Typed):
expected_type = float
class UnsignedFloat(Float, Unsigned):
pass
class String(Typed):
expected_type = str
class SizedString(String, MaxSized):
pass
class Stock:
# Specify constraints
name = SizedString('name', size=8)
shares = UnsignedInteger('shares')
price = UnsignedFloat('price')
def __init__(self, name, shares, price):
self.name = name
self.shares = shares
self.price = price
s = Stock('ACME', 50, 91.1)
# Class decorator to apply constraints
def check_attributes(**kwargs):
def decorate(cls):
for key, value in kwargs.items():
if isinstance(value, Descriptor):
value.name = key
setattr(cls, key, value)
else:
setattr(cls, key, value(key))
return cls
return decorate
# Example
@check_attributes(name=SizedString(size=8),
shares=UnsignedInteger,
price=UnsignedFloat)
class Stock:
def __init__(self, name, shares, price):
self.name = name
self.shares = shares
self.price = price
# A metaclass that applies checking
class checkedmeta(type):
def __new__(cls, clsname, bases, methods):
# Attach attribute names to the descriptors
for key, value in methods.items():
if isinstance(value, Descriptor):
value.name = key
return type.__new__(cls, clsname, bases, methods)
# Example
class Stock2(metaclass=checkedmeta):
name = SizedString(size=8)
shares = UnsignedInteger()
price = UnsignedFloat()
def __init__(self, name, shares, price):
self.name = name
self.shares = shares
self.price = price
# Base class. Uses a descriptor to set a value
class Descriptor:
def __init__(self, name=None, **opts):
self.name = name
for key, value in opts.items():
setattr(self, key, value)
def __set__(self, instance, value):
instance.__dict__[self.name] = value
# Decorator for applying type checking
def Typed(expected_type, cls=None):
if cls is None:
return lambda cls: Typed(expected_type, cls)
super_set = cls.__set__
def __set__(self, instance, value):
if not isinstance(value, expected_type):
raise TypeError('expected ' + str(expected_type))
super_set(self, instance, value)
cls.__set__ = __set__
return cls
# Decorator for unsigned values
def Unsigned(cls):
super_set = cls.__set__
def __set__(self, instance, value):
if value < 0:
raise ValueError('Expected >= 0')
super_set(self, instance, value)
cls.__set__ = __set__
return cls
# Decorator for allowing sized values
def MaxSized(cls):
super_init = cls.__init__
def __init__(self, name=None, **opts):
if 'size' not in opts:
raise TypeError('missing size option')
super_init(self, name, **opts)
cls.__init__ = __init__
super_set = cls.__set__
def __set__(self, instance, value):
if len(value) >= self.size:
raise ValueError('size must be < ' + str(self.size))
super_set(self, instance, value)
cls.__set__ = __set__
return cls
# Specialized descriptors
@Typed(int)
class Integer(Descriptor):
pass
@Unsigned
class UnsignedInteger(Integer):
pass
@Typed(float)
class Float(Descriptor):
pass
@Unsigned
class UnsignedFloat(Float):
pass
@Typed(str)
class String(Descriptor):
pass
@MaxSized
class SizedString(String):
pass
================================================
FILE: cookbook/c08/p14_custom_container.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 自定义容器
Desc :
"""
import collections
import bisect
class SortedItems(collections.Sequence):
def __init__(self, initial=None):
self._items = sorted(initial) if initial is not None else []
# Required sequence methods
def __getitem__(self, index):
return self._items[index]
def __len__(self):
return len(self._items)
# Method for adding an item in the right location
def add(self, item):
bisect.insort(self._items, item)
items = SortedItems([5, 1, 3])
print(list(items))
print(items[0], items[-1])
items.add(2)
print(list(items))
class Items(collections.MutableSequence):
def __init__(self, initial=None):
self._items = list(initial) if initial is not None else []
# Required sequence methods
def __getitem__(self, index):
print('Getting:', index)
return self._items[index]
def __setitem__(self, index, value):
print('Setting:', index, value)
self._items[index] = value
def __delitem__(self, index):
print('Deleting:', index)
del self._items[index]
def insert(self, index, value):
print('Inserting:', index, value)
self._items.insert(index, value)
def __len__(self):
print('Len')
return len(self._items)
a = Items([1, 2, 3])
print(len(a))
================================================
FILE: cookbook/c08/p15_delegate_attribute.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 属性访问代理
Desc :
"""
class A:
def spam(self, x):
pass
def foo(self):
pass
class B1:
"""简单的代理"""
def __init__(self):
self._a = A()
def spam(self, x):
# Delegate to the internal self._a instance
return self._a.spam(x)
def foo(self):
# Delegate to the internal self._a instance
return self._a.foo()
def bar(self):
pass
class B2:
"""使用__getattr__的代理,代理方法比较多时候"""
def __init__(self):
self._a = A()
def bar(self):
pass
# Expose all of the methods defined on class A
def __getattr__(self, name):
"""这个方法在访问的attribute不存在的时候被调用
the __getattr__() method is actually a fallback method
that only gets called when an attribute is not found"""
return getattr(self._a, name)
b = B2()
b.bar() # Calls B.bar() (exists on B)
b.spam(42) # Calls B.__getattr__('spam') and delegates to A.spam
# A proxy class that wraps around another object, but
# exposes its public attributes
class Proxy:
def __init__(self, obj):
self._obj = obj
# Delegate attribute lookup to internal obj
def __getattr__(self, name):
print('getattr:', name)
return getattr(self._obj, name)
# Delegate attribute assignment
def __setattr__(self, name, value):
if name.startswith('_'):
super().__setattr__(name, value)
else:
print('setattr:', name, value)
setattr(self._obj, name, value)
# Delegate attribute deletion
def __delattr__(self, name):
if name.startswith('_'):
super().__delattr__(name)
else:
print('delattr:', name)
delattr(self._obj, name)
class Spam:
def __init__(self, x):
self.x = x
def bar(self, y):
print('Spam.bar:', self.x, y)
# Create an instance
s = Spam(2)
# Create a proxy around it
p = Proxy(s)
# Access the proxy
print(p.x) # Outputs 2
p.bar(3) # Outputs "Spam.bar: 2 3"
p.x = 37 # Changes s.x to 37
class ListLike:
"""__getattr__对于双下划线开始和结尾的方法是不能用的,需要一个个去重定义"""
def __init__(self):
self._items = []
def __getattr__(self, name):
return getattr(self._items, name)
# Added special methods to support certain list operations
def __len__(self):
return len(self._items)
def __getitem__(self, index):
return self._items[index]
def __setitem__(self, index, value):
self._items[index] = value
def __delitem__(self, index):
del self._items[index]
a = ListLike()
a.append(2)
a.insert(0, 1)
a.sort()
print(len(a))
class A:
def spam(self, x):
print('A.spam', x)
def foo(self):
print('A.foo')
class B(A):
def spam(self, x):
print('B.spam')
super().spam(x)
def bar(self):
print('B.bar')
class A:
def spam(self, x):
print('A.spam', x)
def foo(self):
print('A.foo')
class B:
def __init__(self):
self._a = A()
def spam(self, x):
print('B.spam', x)
self._a.spam(x)
def bar(self):
print('B.bar')
def __getattr__(self, name):
return getattr(self._a, name)
================================================
FILE: cookbook/c08/p16_more_constructor.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 定义类的多个构造函数
Desc :
"""
import time
class Date:
"""方法一:使用类方法"""
# Primary constructor
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
# Alternate constructor
@classmethod
def today(cls):
t = time.localtime()
return cls(t.tm_year, t.tm_mon, t.tm_mday)
a = Date(2012, 12, 21) # Primary
b = Date.today() # Alternate
================================================
FILE: cookbook/c08/p17_without_init.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 不使用__init__方法初创建对象
Desc :
"""
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
data = {'year': 2012, 'month': 8, 'day': 29}
d = Date.__new__(Date)
for key, value in data.items():
setattr(d, key, value)
print(d.year, d.month, d.day)
from time import localtime
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
@classmethod
def today(cls):
d = cls.__new__(cls)
t = localtime()
d.year = t.tm_year
d.month = t.tm_mon
d.day = t.tm_mday
return d
================================================
FILE: cookbook/c08/p18_mixin_classes.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 混入类
Desc : 如果单独使用Minxin类没有任何意义,但是当利用多继承和其他类配合后就有神奇效果了。
Mixin也是多继承的主要用途。
"""
class LoggedMappingMixin:
"""
Add logging to get/set/delete operations for debugging.
"""
__slots__ = () # 混入类都没有实例变量,因为直接实例化混入类没有任何意义
def __getitem__(self, key):
print('Getting ' + str(key))
return super().__getitem__(key)
def __setitem__(self, key, value):
print('Setting {} = {!r}'.format(key, value))
return super().__setitem__(key, value)
def __delitem__(self, key):
print('Deleting ' + str(key))
return super().__delitem__(key)
class SetOnceMappingMixin:
'''
Only allow a key to be set once.
'''
__slots__ = ()
def __setitem__(self, key, value):
if key in self:
raise KeyError(str(key) + ' already set')
return super().__setitem__(key, value)
class StringKeysMappingMixin:
'''
Restrict keys to strings only
'''
__slots__ = ()
def __setitem__(self, key, value):
if not isinstance(key, str):
raise TypeError('keys must be strings')
return super().__setitem__(key, value)
class LoggedDict(LoggedMappingMixin, dict):
pass
d = LoggedDict()
d['x'] = 23
print(d['x'])
del d['x']
from collections import defaultdict
class SetOnceDefaultDict(SetOnceMappingMixin, defaultdict):
pass
d = SetOnceDefaultDict(list)
d['x'].append(2)
d['x'].append(3)
# d['x'] = 23 # KeyError: 'x already set'
def LoggedMapping(cls):
"""第二种方式:使用类装饰器"""
cls_getitem = cls.__getitem__
cls_setitem = cls.__setitem__
cls_delitem = cls.__delitem__
def __getitem__(self, key):
print('Getting ' + str(key))
return cls_getitem(self, key)
def __setitem__(self, key, value):
print('Setting {} = {!r}'.format(key, value))
return cls_setitem(self, key, value)
def __delitem__(self, key):
print('Deleting ' + str(key))
return cls_delitem(self, key)
cls.__getitem__ = __getitem__
cls.__setitem__ = __setitem__
cls.__delitem__ = __delitem__
return cls
@LoggedMapping
class LoggedDict(dict):
pass
================================================
FILE: cookbook/c08/p19_stateful_object.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 实现状态对象或状态机
Desc :
"""
class Connection:
"""普通方案,好多个判断语句,效率低下~~"""
def __init__(self):
self.state = 'CLOSED'
def read(self):
if self.state != 'OPEN':
raise RuntimeError('Not open')
print('reading')
def write(self, data):
if self.state != 'OPEN':
raise RuntimeError('Not open')
print('writing')
def open(self):
if self.state == 'OPEN':
raise RuntimeError('Already open')
self.state = 'OPEN'
def close(self):
if self.state == 'CLOSED':
raise RuntimeError('Already closed')
self.state = 'CLOSED'
class Connection1:
"""新方案——对每个状态定义一个类"""
def __init__(self):
self.new_state(ClosedConnectionState)
def new_state(self, newstate):
self._state = newstate
# Delegate to the state class
def read(self):
return self._state.read(self)
def write(self, data):
return self._state.write(self, data)
def open(self):
return self._state.open(self)
def close(self):
return self._state.close(self)
# Connection state base class
class ConnectionState:
@staticmethod
def read(conn):
raise NotImplementedError()
@staticmethod
def write(conn, data):
raise NotImplementedError()
@staticmethod
def open(conn):
raise NotImplementedError()
@staticmethod
def close(conn):
raise NotImplementedError()
# Implementation of different states
class ClosedConnectionState(ConnectionState):
@staticmethod
def read(conn):
raise RuntimeError('Not open')
@staticmethod
def write(conn, data):
raise RuntimeError('Not open')
@staticmethod
def open(conn):
conn.new_state(OpenConnectionState)
@staticmethod
def close(conn):
raise RuntimeError('Already closed')
class OpenConnectionState(ConnectionState):
@staticmethod
def read(conn):
print('reading')
@staticmethod
def write(conn, data):
print('writing')
@staticmethod
def open(conn):
raise RuntimeError('Already open')
@staticmethod
def close(conn):
conn.new_state(ClosedConnectionState)
c = Connection1()
print(c._state)
c.open()
# Alternative implementation
class State:
def __init__(self):
self.new_state(State_A)
def new_state(self, state):
self.__class__ = state
def action(self, x):
raise NotImplementedError()
class State_A(State):
def action(self, x):
# Action for A
pass
self.new_state(State_B)
class State_B(State):
def action(self, x):
# Action for B
pass
self.new_state(State_C)
class State_C(State):
def action(self, x):
# Action for C
pass
self.new_state(State_A)
================================================
FILE: cookbook/c08/p20_invoke_bystr.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 通过字符串调用方法
Desc :
"""
import math
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
# !r表示调用后面参数的__repr__()方法
return 'Point({!r:},{!r:})'.format(self.x, self.y)
def distance(self, x, y):
return math.hypot(self.x - x, self.y - y)
p = Point(2, 3)
d = getattr(p, 'distance')(0, 0) # Calls p.distance(0, 0)
import operator
operator.methodcaller('distance', 0, 0)(p)
points = [
Point(1, 2),
Point(3, 0),
Point(10, -3),
Point(-5, -7),
Point(-1, 8),
Point(3, 2)
]
# Sort by distance from origin (0, 0)
points.sort(key=operator.methodcaller('distance', 0, 0))
================================================
FILE: cookbook/c08/p21_vistor_pattern.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 观察者模式
Desc :
"""
class Node:
pass
class UnaryOperator(Node):
def __init__(self, operand):
self.operand = operand
class BinaryOperator(Node):
def __init__(self, left, right):
self.left = left
self.right = right
class Add(BinaryOperator):
pass
class Sub(BinaryOperator):
pass
class Mul(BinaryOperator):
pass
class Div(BinaryOperator):
pass
class Negate(UnaryOperator):
pass
class Number(Node):
def __init__(self, value):
self.value = value
# Representation of 1 + 2 * (3 - 4) / 5
t1 = Sub(Number(3), Number(4))
t2 = Mul(Number(2), t1)
t3 = Div(t2, Number(5))
t4 = Add(Number(1), t3)
class NodeVisitor:
def visit(self, node):
methname = 'visit_' + type(node).__name__
meth = getattr(self, methname, None)
if meth is None:
meth = self.generic_visit
return meth(node)
def generic_visit(self, node):
raise RuntimeError('No {} method'.format('visit_' + type(node).__name__))
class Evaluator(NodeVisitor):
def visit_Number(self, node):
return node.value
def visit_Add(self, node):
return self.visit(node.left) + self.visit(node.right)
def visit_Sub(self, node):
return self.visit(node.left) - self.visit(node.right)
def visit_Mul(self, node):
return self.visit(node.left) * self.visit(node.right)
def visit_Div(self, node):
return self.visit(node.left) / self.visit(node.right)
def visit_Negate(self, node):
return -node.operand
e = Evaluator()
print(e.visit(t4))
class StackCode(NodeVisitor):
def generate_code(self, node):
self.instructions = []
self.visit(node)
return self.instructions
def visit_Number(self, node):
self.instructions.append(('PUSH', node.value))
def binop(self, node, instruction):
self.visit(node.left)
self.visit(node.right)
self.instructions.append((instruction,))
def visit_Add(self, node):
self.binop(node, 'ADD')
def visit_Sub(self, node):
self.binop(node, 'SUB')
def visit_Mul(self, node):
self.binop(node, 'MUL')
def visit_Div(self, node):
self.binop(node, 'DIV')
def unaryop(self, node, instruction):
self.visit(node.operand)
self.instructions.append((instruction,))
def visit_Negate(self, node):
self.unaryop(node, 'NEG')
class HTTPHandler:
def handle(self, request):
methname = 'do_' + request.request_method
getattr(self, methname)(request)
def do_GET(self, request):
pass
def do_POST(self, request):
pass
def do_HEAD(self, request):
pass
================================================
FILE: cookbook/c08/p22_vistor_norecursiion.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 非递归的观察者模式
Desc :
"""
import types
class Node:
pass
class NodeVisitor:
def visit(self, node):
stack = [node]
last_result = None
while stack:
try:
last = stack[-1]
if isinstance(last, types.GeneratorType):
stack.append(last.send(last_result))
last_result = None
elif isinstance(last, Node):
stack.append(self._visit(stack.pop()))
else:
last_result = stack.pop()
except StopIteration:
stack.pop()
return last_result
def _visit(self, node):
methname = 'visit_' + type(node).__name__
meth = getattr(self, methname, None)
if meth is None:
meth = self.generic_visit
return meth(node)
def generic_visit(self, node):
raise RuntimeError('No {} method'.format('visit_' + type(node).__name__))
class UnaryOperator(Node):
def __init__(self, operand):
self.operand = operand
class BinaryOperator(Node):
def __init__(self, left, right):
self.left = left
self.right = right
class Add(BinaryOperator):
pass
class Sub(BinaryOperator):
pass
class Mul(BinaryOperator):
pass
class Div(BinaryOperator):
pass
class Negate(UnaryOperator):
pass
class Number(Node):
def __init__(self, value):
self.value = value
# A sample visitor class that evaluates expressions
class Evaluator(NodeVisitor):
def visit_Number(self, node):
return node.value
def visit_Add(self, node):
yield (yield node.left) + (yield node.right)
def visit_Sub(self, node):
yield (yield node.left) - (yield node.right)
def visit_Mul(self, node):
yield (yield node.left) * (yield node.right)
def visit_Div(self, node):
yield (yield node.left) / (yield node.right)
def visit_Negate(self, node):
yield - (yield node.operand)
if __name__ == '__main__':
# 1 + 2*(3-4) / 5
t1 = Sub(Number(3), Number(4))
t2 = Mul(Number(2), t1)
t3 = Div(t2, Number(5))
t4 = Add(Number(1), t3)
# Evaluate it
e = Evaluator()
print(e.visit(t4)) # Outputs 0.6
================================================
FILE: cookbook/c08/p23_weakref.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 弱引用
Desc :
"""
import weakref
class Node:
def __init__(self, value):
self.value = value
self._parent = None
self.children = []
def __repr__(self):
return 'Node({!r:})'.format(self.value)
# property that manages the parent as a weak-reference
@property
def parent(self):
return None if self._parent is None else self._parent()
@parent.setter
def parent(self, node):
self._parent = weakref.ref(node)
def add_child(self, child):
self.children.append(child)
child.parent = self
# Class just to illustrate when deletion occurs
class Data:
def __del__(self):
print('Data.__del__')
# Node class involving a cycle
class Node1:
def __init__(self):
self.data = Data()
self.parent = None
self.children = []
def add_child(self, child):
self.children.append(child)
child.parent = self
a = Data()
del a
# print(a) NameError: name 'a' is not defined
a = Node1()
del a
# print(a)
a = Node1()
a.add_child(Node1())
print('--------last del start------------')
del a # Not deleted (no message)
print('--------last del end------------')
# print(a)
print('11111111111111111')
================================================
FILE: cookbook/c08/p24_class_compare.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 类支持比较操作
Desc :
"""
from functools import total_ordering
class Room:
def __init__(self, name, length, width):
self.name = name
self.length = length
self.width = width
self.square_feet = self.length * self.width
@total_ordering
class House:
def __init__(self, name, style):
self.name = name
self.style = style
self.rooms = list()
@property
def living_space_footage(self):
return sum(r.square_feet for r in self.rooms)
def add_room(self, room):
self.rooms.append(room)
def __str__(self):
return '{}: {} square foot {}'.format(self.name,
self.living_space_footage,
self.style)
def __eq__(self, other):
return self.living_space_footage == other.living_space_footage
def __lt__(self, other):
return self.living_space_footage < other.living_space_footage
# Build a few houses, and add rooms to them
h1 = House('h1', 'Cape')
h1.add_room(Room('Master Bedroom', 14, 21))
h1.add_room(Room('Living Room', 18, 20))
h1.add_room(Room('Kitchen', 12, 16))
h1.add_room(Room('Office', 12, 12))
h2 = House('h2', 'Ranch')
h2.add_room(Room('Master Bedroom', 14, 21))
h2.add_room(Room('Living Room', 18, 20))
h2.add_room(Room('Kitchen', 12, 16))
h3 = House('h3', 'Split')
h3.add_room(Room('Master Bedroom', 14, 21))
h3.add_room(Room('Living Room', 18, 20))
h3.add_room(Room('Office', 12, 16))
h3.add_room(Room('Kitchen', 15, 17))
houses = [h1, h2, h3]
print('Is h1 bigger than h2?', h1 > h2) # prints True
print('Is h2 smaller than h3?', h2 < h3) # prints True
print('Is h2 greater than or equal to h1?', h2 >= h1) # Prints False
print('Which one is biggest?', max(houses)) # Prints 'h3: 1101-square-foot Split'
print('Which is smallest?', min(houses)) # Prints 'h2: 846-square-foot Ranch'
================================================
FILE: cookbook/c08/p25_cached_objects.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 创建缓存实例
Desc :
"""
import logging
a = logging.getLogger('foo')
b = logging.getLogger('bar')
print(a is b)
c = logging.getLogger('foo')
print(a is c)
# The class in question
class Spam:
def __init__(self, name):
self.name = name
# Caching support
import weakref
_spam_cache = weakref.WeakValueDictionary()
def get_spam(name):
if name not in _spam_cache:
s = Spam(name)
_spam_cache[name] = s
else:
s = _spam_cache[name]
return s
# Note: This code doesn't quite work
class Spam1:
_spam_cache = weakref.WeakValueDictionary()
def __new__(cls, name):
print('Spam1__new__')
if name in cls._spam_cache:
return cls._spam_cache[name]
else:
self = super().__new__(cls)
cls._spam_cache[name] = self
return self
def __init__(self, name):
print('Initializing Spam')
self.name = name
s = Spam1('Dave')
t = Spam1('Dave')
print(s is t)
class CachedSpamManager:
def __init__(self):
self._cache = weakref.WeakValueDictionary()
def get_spam(self, name):
if name not in self._cache:
s = Spam(name)
self._cache[name] = s
else:
s = self._cache[name]
return s
def clear(self):
self._cache.clear()
class Spam2:
manager = CachedSpamManager()
def __init__(self, name):
self.name = name
def get_spam(name):
return Spam2.manager.get_spam(name)
# ------------------------最后的修正方案------------------------
class CachedSpamManager2:
def __init__(self):
self._cache = weakref.WeakValueDictionary()
def get_spam(self, name):
if name not in self._cache:
temp = Spam3._new(name) # Modified creation
self._cache[name] = temp
else:
temp = self._cache[name]
return temp
def clear(self):
self._cache.clear()
class Spam3:
def __init__(self, *args, **kwargs):
raise RuntimeError("Can't instantiate directly")
# Alternate constructor
@classmethod
def _new(cls, name):
self = cls.__new__(cls)
self.name = name
return self
print('------------------------------')
cachedSpamManager = CachedSpamManager2()
s = cachedSpamManager.get_spam('Dave')
t = cachedSpamManager.get_spam('Dave')
print(s is t)
================================================
FILE: cookbook/c09/__init__.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: sample
Desc :
"""
================================================
FILE: cookbook/c09/p01_wrap_function.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 包装函数
Desc :
"""
import time
from functools import wraps
def timethis(func):
'''
Decorator that reports the execution time.
'''
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(func.__name__, end-start)
return result
return wrapper
@timethis
def countdown(n):
"""
Counts down
"""
while n > 0:
n -= 1
countdown(100000)
countdown(10000000)
================================================
FILE: cookbook/c09/p02_preserve_metadata.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 创建装饰器时保留函数元信息
Desc :
"""
import time
from functools import wraps
def timethis(func):
"""
Decorator that reports the execution time.
"""
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(func.__name__, end - start)
return result
return wrapper
@timethis
def countdown(n: int):
"""
Counts down
"""
while n > 0:
n -= 1
print(countdown.__name__)
print(countdown.__doc__)
print(countdown.__annotations__)
from inspect import signature
print(signature(countdown))
================================================
FILE: cookbook/c09/p03_unwrap_decorator.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 解除包装器
Desc :
"""
from functools import wraps
def decorator1(func):
@wraps(func)
def wrapper(*args, **kwargs):
print('Decorator 1')
return func(*args, **kwargs)
return wrapper
def decorator2(func):
@wraps(func)
def wrapper(*args, **kwargs):
print('Decorator 2')
return func(*args, **kwargs)
return wrapper
@decorator1
@decorator2
def add(x, y):
return x + y
add(1, 2)
print('-----------------')
print(add.__wrapped__(2, 3))
================================================
FILE: cookbook/c09/p04_decorator_argument.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 带有参数的装饰器
Desc :
"""
from functools import wraps
import logging
def logged(level, name=None, message=None):
"""
Add logging to a function. level is the logging
level, name is the logger name, and message is the
log message. If name and message aren't specified,
they default to the function's module and name.
"""
def decorate(func):
logname = name if name else func.__module__
log = logging.getLogger(logname)
logmsg = message if message else func.__name__
@wraps(func)
def wrapper(*args, **kwargs):
log.log(level, logmsg)
return func(*args, **kwargs)
return wrapper
return decorate
# Example use
@logged(logging.DEBUG)
def add(x, y):
return x + y
@logged(logging.CRITICAL, 'example')
def spam():
print('Spam!')
================================================
FILE: cookbook/c09/p05_adjust_attribute.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 可调整属性的装饰器
Desc :
"""
from functools import wraps, partial
import logging
import time
# Utility decorator to attach a function as an attribute of obj
def attach_wrapper(obj, func=None):
if func is None:
return partial(attach_wrapper, obj)
setattr(obj, func.__name__, func)
# return func
def logged(level, name=None, message=None):
"""
Add logging to a function. level is the logging
level, name is the logger name, and message is the
log message. If name and message aren't specified,
they default to the function's module and name.
"""
def decorate(func):
logname = name if name else func.__module__
log = logging.getLogger(logname)
logmsg = message if message else func.__name__
@wraps(func)
def wrapper(*args, **kwargs):
log.log(level, logmsg)
return func(*args, **kwargs)
# Attach setter functions
@attach_wrapper(wrapper)
def set_level(newlevel):
nonlocal level
level = newlevel
@attach_wrapper(wrapper)
def set_message(newmsg):
nonlocal logmsg
logmsg = newmsg
return wrapper
return decorate
# Example use
@logged(logging.DEBUG)
def add(x, y):
return x + y
@logged(logging.CRITICAL, 'example')
def spam():
print('Spam!')
logging.basicConfig(level=logging.DEBUG)
add(2, 3)
add.set_message('Add called')
add(2, 3)
add.set_level(logging.WARNING)
add(2, 3)
print('---------------------')
spam()
spam.set_message('Add called')
spam()
spam.set_level(logging.WARNING)
spam()
def timethis(func):
"""
Decorator that reports the execution time.
"""
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(func.__name__, end - start)
return result
return wrapper
@logged(logging.DEBUG)
@timethis
def countdown(n):
while n > 0:
n -= 1
countdown(10000000)
countdown.set_level(logging.WARNING)
countdown.set_message("Counting down to zero")
countdown(10000000)
@timethis
@logged(logging.DEBUG)
def countdown1(n):
while n > 0:
n -= 1
print('****************************************')
countdown1(10000000)
countdown1.set_level(logging.WARNING)
countdown1.set_message("Counting down to zero")
countdown1(10000000)
================================================
FILE: cookbook/c09/p06_optarg_decorator.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 带可选参数的装饰器
Desc :
"""
from functools import wraps, partial
import logging
def logged(func=None, *, level=logging.DEBUG, name=None, message=None):
if func is None:
return partial(logged, level=level, name=name, message=message)
logname = name if name else func.__module__
log = logging.getLogger(logname)
logmsg = message if message else func.__name__
@wraps(func)
def wrapper(*args, **kwargs):
log.log(level, logmsg)
return func(*args, **kwargs)
return wrapper
# Example use
@logged
def add(x, y):
return x + y
@logged(level=logging.CRITICAL, name='example')
def spam():
print('Spam!')
spam()
def aa(kk=None, *, a=1,b=2,c=3):
print(kk, a, b, c)
bbb = partial(aa, a=1,b=2,c=3)
bbb('333')
================================================
FILE: cookbook/c09/p07_typecheck.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 函数参数强制类型检查
Desc :
"""
from inspect import signature
from functools import wraps
def typeassert(*ty_args, **ty_kwargs):
def decorate(func):
# If in optimized mode, disable type checking
if not __debug__:
return func
# Map function argument names to supplied types
sig = signature(func)
bound_types = sig.bind_partial(*ty_args, **ty_kwargs).arguments
@wraps(func)
def wrapper(*args, **kwargs):
bound_values = sig.bind(*args, **kwargs)
# Enforce type assertions across supplied arguments
for name, value in bound_values.arguments.items():
if name in bound_types:
if not isinstance(value, bound_types[name]):
raise TypeError(
'Argument {} must be {}'.format(name, bound_types[name]))
return func(*args, **kwargs)
return wrapper
return decorate
@typeassert(int, int)
def add(x, y):
return x + y
add(2, 3)
# add(2, '22')
@typeassert(int, list)
def bar(x, items=None):
if items is None:
items = []
items.append(x)
return items
bar(2)
bar(2, [1, 2, 3])
================================================
FILE: cookbook/c09/p08_inclass_decorator.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 类中定义装饰器
Desc :
"""
from functools import wraps
class A:
# Decorator as an instance method
def decorator1(self, func):
@wraps(func)
def wrapper(*args, **kwargs):
print('Decorator 1')
return func(*args, **kwargs)
return wrapper
# Decorator as a class method
@classmethod
def decorator2(cls, func):
@wraps(func)
def wrapper(*args, **kwargs):
print('Decorator 2')
return func(*args, **kwargs)
return wrapper
class Person:
# Create a property instance
first_name = property()
# Apply decorator methods
@first_name.getter
def first_name(self):
return self._first_name
@first_name.setter
def first_name(self, value):
if not isinstance(value, str):
raise TypeError('Expected a string')
self._first_name = value
================================================
FILE: cookbook/c09/p09_class_decorator.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 将装饰器定义成类
Desc :
"""
import types
from functools import wraps
class Profiled:
def __init__(self, func):
wraps(func)(self)
self.ncalls = 0
def __call__(self, *args, **kwargs):
self.ncalls += 1
return self.__wrapped__(*args, **kwargs)
def __get__(self, instance, cls):
if instance is None:
return self
else:
return types.MethodType(self, instance)
@Profiled
def add(x, y):
return x + y
class Spam:
@Profiled
def bar(self, x):
print(self, x)
Spam().bar(3)
import types
from functools import wraps
def profiled(func):
ncalls = 0
@wraps(func)
def wrapper(*args, **kwargs):
nonlocal ncalls
ncalls += 1
return func(*args, **kwargs)
wrapper.ncalls = lambda: ncalls
return wrapper
# Example
@profiled
def add(x, y):
return x + y
================================================
FILE: cookbook/c09/p10_static_decorator.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: sample
Desc :
"""
import time
from functools import wraps
# A simple decorator
def timethis(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
r = func(*args, **kwargs)
end = time.time()
print(end-start)
return r
return wrapper
# Class illustrating application of the decorator to different kinds of methods
class Spam:
@timethis
def instance_method(self, n):
print(self, n)
while n > 0:
n -= 1
@classmethod
@timethis
def class_method(cls, n):
print(cls, n)
while n > 0:
n -= 1
@staticmethod
@timethis
def static_method(n):
print(n)
while n > 0:
n -= 1
from abc import ABCMeta, abstractmethod
class A(metaclass=ABCMeta):
@classmethod
@abstractmethod
def method(cls):
pass
================================================
FILE: cookbook/c09/p11_add_argument.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 给被包装函数增加参数
Desc :
"""
from functools import wraps
import inspect
def optional_debug(func):
@wraps(func)
def wrapper(*args, debug=False, **kwargs):
if debug:
print('Calling', func.__name__)
return func(*args, **kwargs)
return wrapper
@optional_debug
def spam(a, b, c):
print(a, b, c)
spam(1, 2, 3)
spam(1, 2, 3, debug=True)
def a(x, debug=False):
if debug:
print('Calling a')
def b(x, y, z, debug=False):
if debug:
print('Calling b')
def c(x, y, debug=False):
if debug:
print('Calling c')
def optional_debug(func):
if 'debug' in inspect.getargspec(func).args:
raise TypeError('debug argument already defined')
@wraps(func)
def wrapper(*args, debug=False, **kwargs):
if debug:
print('Calling', func.__name__)
return func(*args, **kwargs)
return wrapper
@optional_debug
def a(x):
pass
@optional_debug
def b(x, y, z):
pass
@optional_debug
def c(x, y):
pass
def optional_debug1(func):
if 'debug' in inspect.getargspec(func).args:
raise TypeError('debug argument already defined')
@wraps(func)
def wrapper(*args, debug=False, **kwargs):
if debug:
print('Calling', func.__name__)
return func(*args, **kwargs)
sig = inspect.signature(func)
parms = list(sig.parameters.values())
parms.append(inspect.Parameter('debug',
inspect.Parameter.KEYWORD_ONLY,
default=False))
wrapper.__signature__ = sig.replace(parameters=parms)
return wrapper
@optional_debug1
def add(x,y):
return x+y
print(inspect.signature(add))
================================================
FILE: cookbook/c09/p12_patch_class.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 使用类装饰器来增强类功能
Desc :
"""
def log_getattribute(cls):
# Get the original implementation
orig_getattribute = cls.__getattribute__
# Make a new definition
def new_getattribute(self, name):
print('getting:', name)
return orig_getattribute(self, name)
# Attach to the class and return
cls.__getattribute__ = new_getattribute
return cls
# Example use
@log_getattribute
class A:
def __init__(self, x):
self.x = x
def spam(self):
pass
================================================
FILE: cookbook/c09/p13_instance_create.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 通过元类控制实例的创建
Desc :
"""
class NoInstances(type):
def __call__(self, *args, **kwargs):
raise TypeError("Can't instantiate directly")
# Example
class Spam(metaclass=NoInstances):
@staticmethod
def grok(x):
print('Spam.grok')
class Singleton(type):
def __init__(self, *args, **kwargs):
self.__instance = None
super().__init__(*args, **kwargs)
def __call__(self, *args, **kwargs):
if self.__instance is None:
self.__instance = super().__call__(*args, **kwargs)
return self.__instance
else:
return self.__instance
# Example
class Spam1(metaclass=Singleton):
def __init__(self):
print('Creating Spam')
import weakref
class Cached(type):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__cache = weakref.WeakValueDictionary()
def __call__(self, *args):
if args in self.__cache:
return self.__cache[args]
else:
obj = super().__call__(*args)
self.__cache[args] = obj
return obj
# Example
class Spam2(metaclass=Cached):
def __init__(self, name):
print('Creating Spam({!r})'.format(name))
self.name = name
================================================
FILE: cookbook/c09/p14_attribute_order.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 类定义中属性的顺序
Desc :
"""
from collections import OrderedDict
# A set of descriptors for various types
class Typed:
_expected_type = type(None)
def __init__(self, name=None):
self._name = name
def __set__(self, instance, value):
if not isinstance(value, self._expected_type):
raise TypeError('Expected ' + str(self._expected_type))
instance.__dict__[self._name] = value
class Integer(Typed):
_expected_type = int
class Float(Typed):
_expected_type = float
class String(Typed):
_expected_type = str
# Metaclass that uses an OrderedDict for class body
class OrderedMeta(type):
def __new__(cls, clsname, bases, clsdict):
d = dict(clsdict)
order = []
for name, value in clsdict.items():
if isinstance(value, Typed):
value._name = name
order.append(name)
d['_order'] = order
return type.__new__(cls, clsname, bases, d)
@classmethod
def __prepare__(cls, clsname, bases):
return OrderedDict()
class Structure(metaclass=OrderedMeta):
def as_csv(self):
return ','.join(str(getattr(self, name)) for name in self._order)
# Example use
class Stock(Structure):
name = String()
shares = Integer()
price = Float()
def __init__(self, name, shares, price):
self.name = name
self.shares = shares
self.price = price
================================================
FILE: cookbook/c09/p15_meta_optional_arg.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 元类中的可选参数
Desc :
"""
from abc import ABCMeta, abstractmethod
class IStream(metaclass=ABCMeta):
@abstractmethod
def read(self, maxsize=None):
pass
@abstractmethod
def write(self, data):
pass
class MyMeta(type):
# Optional
@classmethod
def __prepare__(cls, name, bases, *, debug=False, synchronize=False):
# Custom processing
pass
return super().__prepare__(name, bases)
# Required
def __new__(cls, name, bases, ns, *, debug=False, synchronize=False):
# Custom processing
pass
return super().__new__(cls, name, bases, ns)
# Required
def __init__(self, name, bases, ns, *, debug=False, synchronize=False):
# Custom processing
pass
super().__init__(name, bases, ns)
================================================
FILE: cookbook/c09/p16_enforce_args.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 强制*args和**kwargs的参数签名
Desc :
"""
from inspect import Signature, Parameter
def make_sig(*names):
parms = [Parameter(name, Parameter.POSITIONAL_OR_KEYWORD)
for name in names]
return Signature(parms)
class Structure:
__signature__ = make_sig()
def __init__(self, *args, **kwargs):
bound_values = self.__signature__.bind(*args, **kwargs)
for name, value in bound_values.arguments.items():
setattr(self, name, value)
# Example use
class Stock(Structure):
__signature__ = make_sig('name', 'shares', 'price')
class Point(Structure):
__signature__ = make_sig('x', 'y')
from inspect import Signature, Parameter
def make_sig(*names):
parms = [Parameter(name, Parameter.POSITIONAL_OR_KEYWORD)
for name in names]
return Signature(parms)
class StructureMeta(type):
def __new__(cls, clsname, bases, clsdict):
clsdict['__signature__'] = make_sig(*clsdict.get('_fields', []))
return super().__new__(cls, clsname, bases, clsdict)
class Structure(metaclass=StructureMeta):
_fields = []
def __init__(self, *args, **kwargs):
bound_values = self.__signature__.bind(*args, **kwargs)
for name, value in bound_values.arguments.items():
setattr(self, name, value)
# Example
class Stock(Structure):
_fields = ['name', 'shares', 'price']
class Point(Structure):
_fields = ['x', 'y']
================================================
FILE: cookbook/c09/p17_code_convention.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 强制编码规约
Desc :
"""
class MyMeta(type):
def __init__(self, clsname, bases, clsdict):
super().__init__(clsname, bases, clsdict)
# clsname is name of class being defined
# bases is tuple of base classes
# clsdict is class dictionary
class Root(metaclass=MyMeta):
pass
class A(Root):
pass
class B(Root):
pass
class NoMixedCaseMeta(type):
def __new__(cls, clsname, bases, clsdict):
for name in clsdict:
if name.lower() != name:
raise TypeError('Bad attribute name: ' + name)
return super().__new__(cls, clsname, bases, clsdict)
class Root(metaclass=NoMixedCaseMeta):
pass
class A(Root):
def foo_bar(self): # Ok
pass
class B(Root):
def fooBar(self): # TypeError
pass
from inspect import signature
import logging
class MatchSignaturesMeta(type):
def __init__(self, clsname, bases, clsdict):
super().__init__(clsname, bases, clsdict)
sup = super(self, self)
for name, value in clsdict.items():
if name.startswith('_') or not callable(value):
continue
# Get the previous definition (if any) and compare the signatures
prev_dfn = getattr(sup,name,None)
if prev_dfn:
prev_sig = signature(prev_dfn)
val_sig = signature(value)
if prev_sig != val_sig:
logging.warning('Signature mismatch in %s. %s != %s',
value.__qualname__, prev_sig, val_sig)
# Example
class Root(metaclass=MatchSignaturesMeta):
pass
class A(Root):
def foo(self, x, y):
pass
def spam(self, x, *, z):
pass
# Class with redefined methods, but slightly different signatures
class B(A):
def foo(self, a, b):
pass
def spam(self,x,z):
pass
================================================
FILE: cookbook/c09/p18_define_classes.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 以编程方式定义类
Desc :
"""
# stock.py
# Example of making a class manually from parts
# Methods
def __init__(self, name, shares, price):
self.name = name
self.shares = shares
self.price = price
def cost(self):
return self.shares * self.price
cls_dict = {
'__init__': __init__,
'cost': cost,
}
# Make a class
import types
Stock = types.new_class('Stock', (), {}, lambda ns: ns.update(cls_dict))
Stock.__module__ = __name__
import operator
import types
import sys
def named_tuple(classname, fieldnames):
# Populate a dictionary of field property accessors
cls_dict = {name: property(operator.itemgetter(n))
for n, name in enumerate(fieldnames)}
# Make a __new__ function and add to the class dict
def __new__(cls, *args):
if len(args) != len(fieldnames):
raise TypeError('Expected {} arguments'.format(len(fieldnames)))
return tuple.__new__(cls, args)
cls_dict['__new__'] = __new__
# Make the class
cls = types.new_class(classname, (tuple,), {},
lambda ns: ns.update(cls_dict))
# Set the module to that of the caller
cls.__module__ = sys._getframe(1).f_globals['__name__']
return cls
================================================
FILE: cookbook/c09/p19_define_init.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 在定义的时候初始化类的成员
Desc :
"""
import operator
class StructTupleMeta(type):
def __init__(cls, *args, **kwargs):
super().__init__(*args, **kwargs)
for n, name in enumerate(cls._fields):
setattr(cls, name, property(operator.itemgetter(n)))
class StructTuple(tuple, metaclass=StructTupleMeta):
_fields = []
def __new__(cls, *args):
if len(args) != len(cls._fields):
raise ValueError('{} arguments required'.format(len(cls._fields)))
return super().__new__(cls, args)
class Stock(StructTuple):
_fields = ['name', 'shares', 'price']
class Point(StructTuple):
_fields = ['x', 'y']
================================================
FILE: cookbook/c09/p20_multiple_dispatch.py
================================================
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 利用函数注解实现方法重载
Desc :
"""
# multiple.py
import inspect
import types
class MultiMethod:
'''
Represents a single multimethod.
'''
def __init__(self, name):
self._methods = {}
self.__name__ = name
def register(self, meth):
'''
Register a new method as a multimethod
'''
sig = inspect.signature(meth)
# Build a type signature from the method's annotations
types = []
for name, parm in sig.parameters.items():
if name == 'self':
continue
if parm.annotation is inspect.Parameter.empty:
raise TypeError(
'Argument {} must be annotated with a type'.format(name)
)
if not isinstance(parm.annotation, type):
raise TypeError(
'Argument {} annotation must be a type'.format(name)
)
if parm.default is not inspect.Parameter.empty:
self._methods[tuple(types)] = meth
types.append(parm.annotation)
self._methods[tuple(types)] = meth
def __call__(self, *args):
'''
Call a method based on type signature of the arguments
'''
types = tuple(type(arg) for arg in args[1:])
meth = self._methods.get(types, None)
if meth:
return meth(*args)
else:
raise TypeError('No matching method for types {}'.format(types))
def __get__(self, instance, cls):
'''
Descriptor method needed to make calls work in a class
'''
if instance is not None:
return types.MethodType(self, instance)
else:
return self
class MultiDict(dict):
'''
Special dictionary to build multimethods in a metaclass
'''
def __setitem__(self, key, value):
if key in self:
# If key already exists, it must be a multimethod or callable
current_value = self[key]
if isinstance(current_value, MultiMethod):
current_value.register(value)
else:
mvalue = MultiMethod(key)
mvalue.register(current_value)
mvalue.register(value)
super().__setitem__(key, mvalue)
else:
super().__setitem__(key, value)
class MultipleMeta(type):
'''
Metaclass that allows multiple dispatch of methods
'''
def __new__(cls, clsname, bases, clsdict):
return type.__new__(cls, clsname, bases, dict(clsdict))
@classmethod
def __prepare__(cls, clsname, bases):
return MultiDict()
class Spam(metaclass=MultipleMeta):
def bar(self, x:int, y:int):
print('Bar 1:', x, y)
def bar(self, s:str, n:int=0):
print('Bar 2:', s, n)
# Example: overloaded __init__
import time
class Date(metaclass=MultipleMeta):
def __init__(self, year: int, month:int, day:int):
self.year = year
self.month = month
self.day = day
def __init__(self):
t = time.localtime()
self.__init__(t.tm_year, t.tm_mon, t.tm_mday)
i
gitextract_xikm7pk_/
├── .gitignore
├── .travis.yml
├── Makefile
├── README.md
├── README_en.md
├── cookbook/
│ ├── __init__.py
│ ├── c01/
│ │ ├── __init__.py
│ │ ├── p03_nitem.py
│ │ ├── p04_nlargest.py
│ │ ├── p05_priority_queue.py
│ │ ├── p06_multidict.py
│ │ ├── p07_ordered_dict.py
│ │ ├── p08_calculate_dict.py
│ │ ├── p09_dict_common.py
│ │ ├── p10_remove_duplicate.py
│ │ ├── p11_naming_slice.py
│ │ ├── p12_mostfreq_items.py
│ │ ├── p13_sort_dictlist.py
│ │ ├── p14_sort_nocompare.py
│ │ ├── p15_group.py
│ │ ├── p16_filter.py
│ │ ├── p17_subdict.py
│ │ ├── p18_nameseq.py
│ │ ├── p19_trans_reduce.py
│ │ └── p20_combine_map.py
│ ├── c02/
│ │ ├── __init__.py
│ │ ├── p01_splitstr.py
│ │ ├── p02_str_start.py
│ │ ├── p03_unix_match.py
│ │ ├── p04_match_search.py
│ │ ├── p05_search_replace.py
│ │ ├── p06_case_insensitive.py
│ │ ├── p07_shortest_match.py
│ │ ├── p08_multiline_match.py
│ │ ├── p09_normal_unicode.py
│ │ ├── p10_re_unicode.py
│ │ ├── p11_strip.py
│ │ ├── p12_translate.py
│ │ ├── p13_align_str.py
│ │ ├── p14_join_str.py
│ │ ├── p15_var_string.py
│ │ ├── p16_textwrap.py
│ │ ├── p17_html_xml.py
│ │ ├── p18_tokenize.py
│ │ ├── p19_descent_parser.py
│ │ └── p20_byte_str.py
│ ├── c03/
│ │ ├── __init__.py
│ │ ├── p01_round.py
│ │ ├── p02_accurate_decimal.py
│ │ ├── p03_format_number.py
│ │ ├── p04_bin_octal.py
│ │ ├── p05_int_bytes.py
│ │ ├── p06_complex.py
│ │ ├── p07_inf_nan.py
│ │ ├── p08_fraction.py
│ │ ├── p09_array_numpy.py
│ │ ├── p10_matrix_linear.py
│ │ ├── p11_random_num.py
│ │ ├── p12_datatime.py
│ │ ├── p13_last_friday.py
│ │ ├── p14_month_range.py
│ │ ├── p15_str_datetime.py
│ │ └── p16_timezone.py
│ ├── c04/
│ │ ├── __init__.py
│ │ ├── p01_manual_iterator.py
│ │ ├── p02_delegate_iter.py
│ │ ├── p03_generator_pattern.py
│ │ ├── p04_iterator_protocol.py
│ │ ├── p05_reverse_iterate.py
│ │ ├── p06_generator_extrastate.py
│ │ ├── p07_iterator_slice.py
│ │ ├── p08_skip_iterable.py
│ │ ├── p09_iter_permutation.py
│ │ ├── p10_iterate_index.py
│ │ ├── p11_iterate_simultaneous.py
│ │ ├── p12_iterate_separate.py
│ │ ├── p13_process_pipline.py
│ │ ├── p14_flatten_sequence.py
│ │ ├── p15_merge_sorted.py
│ │ └── p16_iterate_while.py
│ ├── c05/
│ │ ├── __init__.py
│ │ ├── p01_rw_text.py
│ │ ├── p02_print_tofile.py
│ │ ├── p03_print_sepend.py
│ │ ├── p04_rw_binary.py
│ │ ├── p05_write_notexist.py
│ │ ├── p06_string_io.py
│ │ ├── p07_gzip_bz2.py
│ │ ├── p08_iterate_fixedsize.py
│ │ ├── p09_read_tobuffer.py
│ │ ├── p10_memery_mapping.py
│ │ ├── p11_pathnames.py
│ │ ├── p12_file_existence.py
│ │ ├── p13_dir_listfile.py
│ │ ├── p14_bypass_encode.py
│ │ ├── p15_print_badfile.py
│ │ ├── p16_change_opencode.py
│ │ ├── p17_bytes_tofile.py
│ │ ├── p18_file_descriptor.py
│ │ ├── p19_temp_file.py
│ │ ├── p20_serial_ports.py
│ │ └── p21_serialize_object.py
│ ├── c06/
│ │ ├── __init__.py
│ │ ├── data.json
│ │ ├── p01_rw_csv.py
│ │ ├── p02_rw_json.py
│ │ ├── p03_simple_xml.py
│ │ ├── p04_huge_xml.py
│ │ ├── p05_dict_toxml.py
│ │ ├── p06_rw_xml.py
│ │ ├── p07_namespace_xml.py
│ │ ├── p08_database.py
│ │ ├── p09_codec_hex.py
│ │ ├── p10_codec_base64.py
│ │ ├── p11_rw_barray.py
│ │ ├── p12_var_binary.py
│ │ ├── pred.xml
│ │ └── stocks.csv
│ ├── c07/
│ │ ├── __init__.py
│ │ ├── p02_keyarg_only.py
│ │ ├── p03_func_annotate.py
│ │ ├── p05_default_argument.py
│ │ ├── p06_anony_func.py
│ │ ├── p08_partial.py
│ │ ├── p09_class_to_func.py
│ │ ├── p10_callback.py
│ │ ├── p11_inline_callback.py
│ │ └── p12_closure_access.py
│ ├── c08/
│ │ ├── __init__.py
│ │ ├── p01_str_represent.py
│ │ ├── p02_custom_format.py
│ │ ├── p03_context_protocol.py
│ │ ├── p04_slots.py
│ │ ├── p05_encapsulate_name.py
│ │ ├── p06_managed_attribute.py
│ │ ├── p07_super_method.py
│ │ ├── p08_extend_property.py
│ │ ├── p09_descriptor.py
│ │ ├── p10_lazy_property.py
│ │ ├── p11_simplify_init.py
│ │ ├── p12_abstract_interface.py
│ │ ├── p13_type_system.py
│ │ ├── p14_custom_container.py
│ │ ├── p15_delegate_attribute.py
│ │ ├── p16_more_constructor.py
│ │ ├── p17_without_init.py
│ │ ├── p18_mixin_classes.py
│ │ ├── p19_stateful_object.py
│ │ ├── p20_invoke_bystr.py
│ │ ├── p21_vistor_pattern.py
│ │ ├── p22_vistor_norecursiion.py
│ │ ├── p23_weakref.py
│ │ ├── p24_class_compare.py
│ │ └── p25_cached_objects.py
│ ├── c09/
│ │ ├── __init__.py
│ │ ├── p01_wrap_function.py
│ │ ├── p02_preserve_metadata.py
│ │ ├── p03_unwrap_decorator.py
│ │ ├── p04_decorator_argument.py
│ │ ├── p05_adjust_attribute.py
│ │ ├── p06_optarg_decorator.py
│ │ ├── p07_typecheck.py
│ │ ├── p08_inclass_decorator.py
│ │ ├── p09_class_decorator.py
│ │ ├── p10_static_decorator.py
│ │ ├── p11_add_argument.py
│ │ ├── p12_patch_class.py
│ │ ├── p13_instance_create.py
│ │ ├── p14_attribute_order.py
│ │ ├── p15_meta_optional_arg.py
│ │ ├── p16_enforce_args.py
│ │ ├── p17_code_convention.py
│ │ ├── p18_define_classes.py
│ │ ├── p19_define_init.py
│ │ ├── p20_multiple_dispatch.py
│ │ ├── p21_avoid_repetitive.py
│ │ ├── p22_context_manager.py
│ │ ├── p23_local_side.py
│ │ ├── p24_analyze_source.py
│ │ └── p25_disassemble_bytecode.py
│ ├── c10/
│ │ ├── __init__.py
│ │ ├── p02_control_import.py
│ │ └── p12_import_patch.py
│ ├── c11/
│ │ ├── p01_.py
│ │ ├── p02_.py
│ │ ├── p03_.py
│ │ ├── p04_.py
│ │ ├── p05_.py
│ │ ├── p06_.py
│ │ ├── p07_.py
│ │ ├── p08_.py
│ │ ├── p09_.py
│ │ ├── p10_.py
│ │ ├── p11_.py
│ │ ├── p12_.py
│ │ └── p13_.py
│ ├── c12/
│ │ ├── __init__.py
│ │ ├── p01_start_stop_thread.py
│ │ ├── p02_.py
│ │ ├── p03_.py
│ │ ├── p04_.py
│ │ ├── p05_.py
│ │ ├── p06_.py
│ │ ├── p07_.py
│ │ ├── p08_.py
│ │ ├── p09_.py
│ │ ├── p10_.py
│ │ ├── p11_.py
│ │ ├── p12_.py
│ │ ├── p13_.py
│ │ └── p14_.py
│ ├── c13/
│ │ ├── p01_.py
│ │ ├── p02_.py
│ │ ├── p03_.py
│ │ ├── p04_.py
│ │ ├── p05_.py
│ │ ├── p06_.py
│ │ ├── p07_.py
│ │ ├── p08_.py
│ │ ├── p09_.py
│ │ ├── p10_.py
│ │ ├── p11_.py
│ │ ├── p12_.py
│ │ ├── p13_.py
│ │ ├── p14_.py
│ │ └── p15_.py
│ ├── c14/
│ │ ├── p01_.py
│ │ ├── p02_.py
│ │ ├── p03_.py
│ │ ├── p04_.py
│ │ ├── p05_.py
│ │ ├── p06_.py
│ │ ├── p07_.py
│ │ ├── p08_.py
│ │ ├── p09_.py
│ │ ├── p10_.py
│ │ ├── p11_.py
│ │ ├── p12_.py
│ │ ├── p13_.py
│ │ └── p14_.py
│ ├── c15/
│ │ ├── p01_.py
│ │ ├── p02_.py
│ │ ├── p03_.py
│ │ ├── p04_.py
│ │ ├── p05_.py
│ │ ├── p06_.py
│ │ ├── p07_.py
│ │ ├── p08_.py
│ │ ├── p09_.py
│ │ ├── p10_.py
│ │ ├── p11_.py
│ │ ├── p12_.py
│ │ ├── p13_.py
│ │ ├── p14_.py
│ │ ├── p15_.py
│ │ ├── p16_.py
│ │ ├── p17_.py
│ │ ├── p18_.py
│ │ ├── p19_.py
│ │ ├── p20_.py
│ │ └── p21_.py
│ └── somefile.txt
├── exts/
│ ├── chinese_search.py
│ ├── main.dic
│ ├── smallseg.py
│ ├── suffix.dic
│ └── zh.py
├── make.bat
├── notebook/
│ ├── fetch_cookbook.py
│ └── ipynb/
│ ├── 第一章:数据结构和算法/
│ │ ├── p01_unpack_sequence_into_separate_variables.ipynb
│ │ ├── p02_unpack_elements_from_iterables.ipynb
│ │ ├── p03_keep_last_n_items.ipynb
│ │ ├── p04_find_largest_or_smallest_n_items.ipynb
│ │ ├── p05_implement_a_priority_queue.ipynb
│ │ ├── p06_map_keys_to_multiple_values_in_dict.ipynb
│ │ ├── p07_keep_dict_in_order.ipynb
│ │ ├── p08_calculating_with_dict.ipynb
│ │ ├── p09_find_commonalities_in_dicts.ipynb
│ │ ├── p10_remove_duplicates_from_seq_order.ipynb
│ │ ├── p11_naming_slice.ipynb
│ │ ├── p12_determine_most_freqently_items_in_seq.ipynb
│ │ ├── p13_sort_list_of_dicts_by_key.ipynb
│ │ ├── p14_sort_objects_without_compare_support.ipynb
│ │ ├── p15_group_records_based_on_field.ipynb
│ │ ├── p16_filter_sequence_elements.ipynb
│ │ ├── p17_extract_subset_of_dict.ipynb
│ │ ├── p18_map_names_to_sequence_elements.ipynb
│ │ ├── p19_transform_and_reduce_data_same_time.ipynb
│ │ └── p20_combine_multiple_map_to_single_map.ipynb
│ ├── 第一章:数据结构和算法.ipynb
│ ├── 第七章:函数/
│ │ ├── p01_functions_that_accept_any_number_arguments.ipynb
│ │ ├── p02_functions_that_only_accept_keyword_arguments.ipynb
│ │ ├── p03_attach_informatinal_matadata_to_function_arguments.ipynb
│ │ ├── p04_return_multiple_values_from_function.ipynb
│ │ ├── p05_define_functions_with_default_arguments.ipynb
│ │ ├── p06_define_anonymous_or_inline_functions.ipynb
│ │ ├── p07_capturing_variables_in_anonymous_functions.ipynb
│ │ ├── p08_make_callable_with_fewer_arguments.ipynb
│ │ ├── p09_replace_single_method_classes_with_functions.ipynb
│ │ ├── p10_carry_extra_state_with_callback_functions.ipynb
│ │ ├── p11_inline_callback_functions.ipynb
│ │ └── p12_access_variables_defined_inside_closure.ipynb
│ ├── 第七章:函数.ipynb
│ ├── 第三章:数字日期和时间/
│ │ ├── p01_round_number.ipynb
│ │ ├── p02_accurate_decimal_calculations.ipynb
│ │ ├── p03_format_numbers_for_output.ipynb
│ │ ├── p04_binary_octal_hexadecimal_int.ipynb
│ │ ├── p05_pack_unpack_large_int_from_bytes.ipynb
│ │ ├── p06_complex_math.ipynb
│ │ ├── p07_infinity_and_nan.ipynb
│ │ ├── p08_calculating_with_fractions.ipynb
│ │ ├── p09_calculating_with_large_num_arrays.ipynb
│ │ ├── p10_matrix_and_linear_algebra_calculation.ipynb
│ │ ├── p11_pick_things_at_random.ipynb
│ │ ├── p12_convert_days_to_seconds_and_others.ipynb
│ │ ├── p13_determine_last_friday_date.ipynb
│ │ ├── p14_date_range_for_current_month.ipynb
│ │ ├── p15_convert_strings_into_datetimes.ipynb
│ │ └── p16_manipulate_dates_involving_timezone.ipynb
│ ├── 第三章:数字日期和时间.ipynb
│ ├── 第九章:元编程/
│ │ ├── p01_put_wrapper_around_function.ipynb
│ │ ├── p02_preserve_function_metadata_when_write_decorators.ipynb
│ │ ├── p03_unwrapping_decorator.ipynb
│ │ ├── p04_define_decorator_that_takes_arguments.ipynb
│ │ ├── p05_define_decorator_with_user_adjustable_attributes.ipynb
│ │ ├── p06_define_decorator_that_takes_optional_argument.ipynb
│ │ ├── p07_enforcing_type_check_on_function_using_decorator.ipynb
│ │ ├── p08_define_decorators_as_part_of_class.ipynb
│ │ ├── p09_define_decorators_as_classes.ipynb
│ │ ├── p10_apply_decorators_to_class_and_static_methods.ipynb
│ │ ├── p11_write_decorators_that_add_arguments_to_functions.ipynb
│ │ ├── p12_using_decorators_to_patch_class_definitions.ipynb
│ │ ├── p13_using_mataclass_to_control_instance_creation.ipynb
│ │ ├── p14_capture_class_attribute_definition_order.ipynb
│ │ ├── p15_define_metaclass_that_takes_optional_arguments.ipynb
│ │ ├── p16_enforce_argument_signature_on_args_kwargs.ipynb
│ │ ├── p17_enforce_coding_conventions_in_classes.ipynb
│ │ ├── p18_define_classes_programmatically.ipynb
│ │ ├── p19_initializing_class_members_at_definition_time.ipynb
│ │ ├── p20_implement_multiple_dispatch_with_function_annotations.ipynb
│ │ ├── p21_avoid_repetitive_property_methods.ipynb
│ │ ├── p22_define_context_managers_the_easy_way.ipynb
│ │ ├── p23_executing_code_with_local_side_effects.ipynb
│ │ ├── p24_parse_and_analyzing_python_source.ipynb
│ │ └── p25_disassembling_python_byte_code.ipynb
│ ├── 第九章:元编程.ipynb
│ ├── 第二章:字符串和文本/
│ │ ├── p01_split_string_on_multiple_delimiters.ipynb
│ │ ├── p02_match_text_at_start_end.ipynb
│ │ ├── p03_match_strings_with_shell_wildcard.ipynb
│ │ ├── p04_match_and_search_text.ipynb
│ │ ├── p05_search_and_replace_text.ipynb
│ │ ├── p06_search_replace_case_insensitive.ipynb
│ │ ├── p07_specify_regexp_for_shortest_match.ipynb
│ │ ├── p08_regexp_for_multiline_partterns.ipynb
│ │ ├── p09_normalize_unicode_text_to_regexp.ipynb
│ │ ├── p10_work_with_unicode_in_regexp.ipynb
│ │ ├── p11_strip_unwanted_characters.ipynb
│ │ ├── p12_sanitizing_clean_up_text.ipynb
│ │ ├── p13_aligning_text_strings.ipynb
│ │ ├── p14_combine_and_concatenate_strings.ipynb
│ │ ├── p15_interpolating_variables_in_strings.ipynb
│ │ ├── p16_reformat_text_to_fixed_number_columns.ipynb
│ │ ├── p17_handle_html_xml_in_text.ipynb
│ │ ├── p18_tokenizing_text.ipynb
│ │ ├── p19_writing_recursive_descent_parser.ipynb
│ │ └── p20_perform_text_operations_on_byte_string.ipynb
│ ├── 第二章:字符串和文本.ipynb
│ ├── 第五章:文件与IO/
│ │ ├── p01_read_write_text_data.ipynb
│ │ ├── p02_printing_to_file.ipynb
│ │ ├── p03_print_with_different_separator_or_line_ending.ipynb
│ │ ├── p04_read_write_binary_data.ipynb
│ │ ├── p05_write_to_file_not_exist.ipynb
│ │ ├── p06_io_operations_on_string.ipynb
│ │ ├── p07_read_write_compressed_datafiles.ipynb
│ │ ├── p08_iterate_over_fixed_sized_records.ipynb
│ │ ├── p09_read_binary_data_into_mutable_buffer.ipynb
│ │ ├── p10_memory_mapping_binary_files.ipynb
│ │ ├── p11_manipulating_pathnames.ipynb
│ │ ├── p12_test_for_the_existence_of_file.ipynb
│ │ ├── p13_get_directory_listing.ipynb
│ │ ├── p14_bypassing_filename_encoding.ipynb
│ │ ├── p15_printing_bad_filenames.ipynb
│ │ ├── p16_add_change_encoding_of_already_open_file.ipynb
│ │ ├── p17_write_bytes_to_text_file.ipynb
│ │ ├── p18_wrap_existing_file_descriptor_as_file_object.ipynb
│ │ ├── p19_make_temporary_files_and_directories.ipynb
│ │ ├── p20_communicating_with_serial_ports.ipynb
│ │ └── p21_serializing_python_objects.ipynb
│ ├── 第五章:文件与IO.ipynb
│ ├── 第八章:类与对象/
│ │ ├── p01_change_string_representation_of_instances.ipynb
│ │ ├── p02_customizing_string_formatting.ipynb
│ │ ├── p03_make_objects_support_context_management_protocol.ipynb
│ │ ├── p04_save_memory_when_create_large_number_instances.ipynb
│ │ ├── p05_encapsulating_names_in_class.ipynb
│ │ ├── p06_create_managed_attributes.ipynb
│ │ ├── p07_calling_method_on_parent_class.ipynb
│ │ ├── p08_extending_property_in_subclass.ipynb
│ │ ├── p09_create_new_kind_of_class_or_instance_attribute.ipynb
│ │ ├── p10_using_lazily_computed_properties.ipynb
│ │ ├── p11_simplify_initialization_of_data_structure.ipynb
│ │ ├── p12_define_interface_or_abstract_base_class.ipynb
│ │ ├── p13_implementing_data_model_or_type_system.ipynb
│ │ ├── p14_implementing_custom_containers.ipynb
│ │ ├── p15_delegating_attribute_access.ipynb
│ │ ├── p16_define_more_than_one_constructor_in_class.ipynb
│ │ ├── p17_create_instance_without_invoking_init_method.ipynb
│ │ ├── p18_extending_classes_with_mixins.ipynb
│ │ ├── p19_implements_stateful_objects_or_state_machines.ipynb
│ │ ├── p20_call_method_on_object_by_string_name.ipynb
│ │ ├── p21_implementing_visitor_pattern.ipynb
│ │ ├── p22_implementing_visitor_pattern_without_recursion.ipynb
│ │ ├── p23_managing_memory_in_cyclic_data_structures.ipynb
│ │ ├── p24_making_classes_support_comparison_operations.ipynb
│ │ └── p25_creating_cached_instances.ipynb
│ ├── 第八章:类与对象.ipynb
│ ├── 第六章:数据编码和处理/
│ │ ├── p01_read_write_csv_data.ipynb
│ │ ├── p02_read-write_json_data.ipynb
│ │ ├── p03_parse_simple_xml_data.ipynb
│ │ ├── p04_parse_huge_xml_files_incrementally.ipynb
│ │ ├── p05_turning_dictionary_into_xml.ipynb
│ │ ├── p06_parse_modify_rewrite_xml.ipynb
│ │ ├── p07_parse_xml_documents_with_namespaces.ipynb
│ │ ├── p08_interact_with_relational_database.ipynb
│ │ ├── p09_decode_encode_hexadecimal_digits.ipynb
│ │ ├── p10_decode_encode_base64.ipynb
│ │ ├── p11_read_write_binary_arrays_of_structures.ipynb
│ │ ├── p12_read_nested_and_variable_sized_binary_structures.ipynb
│ │ └── p13_summarizing_and_perform_statistics.ipynb
│ ├── 第六章:数据编码和处理.ipynb
│ ├── 第十一章:网络与Web编程/
│ │ ├── p01_interact_with_http_services_as_client.ipynb
│ │ ├── p02_creating_tcp_server.ipynb
│ │ ├── p03_creating_udp_server.ipynb
│ │ ├── p04_generate_range_of_ip_addresses_from_cidr_address.ipynb
│ │ ├── p05_creating_simple_rest_based_interface.ipynb
│ │ ├── p06_implement_simple_remote_procedure_call_with_xml_rpc.ipynb
│ │ ├── p07_communicate_simply_between_interpreters.ipynb
│ │ ├── p08_implementing_remote_procedure_calls.ipynb
│ │ ├── p09_authenticating_clients_simply.ipynb
│ │ ├── p10_add_ssl_to_network_services.ipynb
│ │ ├── p11_pass_socket_file_descriptor_between_processes.ipynb
│ │ ├── p12_understanding_event_driven_io.ipynb
│ │ └── p13_sending_receiving_large_arrays.ipynb
│ ├── 第十一章:网络与Web编程.ipynb
│ ├── 第十三章:脚本编程与系统管理/
│ │ ├── p01_accept_input_via_redirect_pips_or_input_files.ipynb
│ │ ├── p02_terminate_program_with_an_error_message.ipynb
│ │ ├── p03_parsing_command_line_options.ipynb
│ │ ├── p04_prompt_for_password_at_runtime.ipynb
│ │ ├── p05_getting_terminal_size.ipynb
│ │ ├── p06_executing_external_command_and_get_its_output.ipynb
│ │ ├── p07_copy_move_files_and_directories.ipynb
│ │ ├── p08_creating_and_unpacking_archives.ipynb
│ │ ├── p09_find_files_by_name.ipynb
│ │ ├── p10_read_configuration_files.ipynb
│ │ ├── p11_add_logging_to_simple_scripts.ipynb
│ │ ├── p12_add_logging_to_libraries.ipynb
│ │ ├── p13_making_stopwatch_timer.ipynb
│ │ ├── p14_putting_limits_on_memory_and_cpu_usage.ipynb
│ │ └── p15_luanch_a_web_browser.ipynb
│ ├── 第十三章:脚本编程与系统管理.ipynb
│ ├── 第十二章:并发编程/
│ │ ├── p01_start_stop_thread.ipynb
│ │ ├── p02_determining_if_thread_has_started.ipynb
│ │ ├── p03_communicating_between_threads.ipynb
│ │ ├── p04_locking_critical_sections.ipynb
│ │ ├── p05_locking_with_deadlock_avoidance.ipynb
│ │ ├── p06_storing_thread_specific_state.ipynb
│ │ ├── p07_creating_thread_pool.ipynb
│ │ ├── p08_perform_simple_parallel_programming.ipynb
│ │ ├── p09_dealing_with_gil_stop_worring_about_it.ipynb
│ │ ├── p10_defining_an_actor_task.ipynb
│ │ ├── p11_implement_publish_subscribe_messaging.ipynb
│ │ ├── p12_using_generators_as_alternative_to_threads.ipynb
│ │ ├── p13_polling_multiple_thread_queues.ipynb
│ │ └── p14_launching_daemon_process_on_unix.ipynb
│ ├── 第十二章:并发编程.ipynb
│ ├── 第十五章:C语言扩展/
│ │ ├── p01_access_ccode_using_ctypes.ipynb
│ │ ├── p02_write_simple_c_extension_module.ipynb
│ │ ├── p03_write_extension_function_operate_on_arrays.ipynb
│ │ ├── p04_manage_opaque_pointers_in_c_extension_modules.ipynb
│ │ ├── p05_define_and_export_c_api_from_extension_modules.ipynb
│ │ ├── p06_calling_python_from_c.ipynb
│ │ ├── p07_release_the_gil_in_c_extensions.ipynb
│ │ ├── p08_mix_threads_from_c_and_python.ipynb
│ │ ├── p09_wrap_c_code_with_swig.ipynb
│ │ ├── p10_wrap_existing_c_code_with_cython.ipynb
│ │ ├── p11_use_cython_to_write_high_performance_array_operation.ipynb
│ │ ├── p12_turning_function_pointer_into_callable.ipynb
│ │ ├── p13_pass_null_terminated_string_to_c_libraries.ipynb
│ │ ├── p14_pass_unicode_strings_to_c_libraries.ipynb
│ │ ├── p15_converting_c_string_to_python.ipynb
│ │ ├── p16_work_with_c_strings_of_dubious_encoding.ipynb
│ │ ├── p17_pass_filenames_to_c_extensions.ipynb
│ │ ├── p18_pass_open_files_to_c_extensions.ipynb
│ │ ├── p19_read_file_like_objects_from_c.ipynb
│ │ ├── p20_consuming_an_iterable_from_c.ipynb
│ │ └── p21_diagnosing_segmentation_faults.ipynb
│ ├── 第十五章:C语言扩展.ipynb
│ ├── 第十四章:测试、调试和异常/
│ │ ├── p01_testing_output_sent_to_stdout.ipynb
│ │ ├── p02_patching_objects_in_unit_tests.ipynb
│ │ ├── p03_testing_for_exceptional_conditions_in_unit_tests.ipynb
│ │ ├── p04_logging_test_output_to_file.ipynb
│ │ ├── p05_skip_or_anticipate_test_failures.ipynb
│ │ ├── p06_handle_multiple_exceptions.ipynb
│ │ ├── p07_catching_all_exceptions.ipynb
│ │ ├── p08_creating_custom_exceptions.ipynb
│ │ ├── p09_raise_exception_in_response_to_another_exception.ipynb
│ │ ├── p10_reraising_the_last_exception.ipynb
│ │ ├── p11_issuing_warning_messages.ipynb
│ │ ├── p12_debugging_basic_program_crashes.ipynb
│ │ ├── p13_profiling_and_timing_your_program.ipynb
│ │ └── p14_make_your_program_run_faster.ipynb
│ ├── 第十四章:测试、调试和异常.ipynb
│ ├── 第十章:模块与包/
│ │ ├── p01_make_hierarchical_package_of_modules.ipynb
│ │ ├── p02_control_the_import_of_everything.ipynb
│ │ ├── p03_import_submodules_by_relative_names.ipynb
│ │ ├── p04_split_module_into_multiple_files.ipynb
│ │ ├── p05_separate_directories_import_by_namespace.ipynb
│ │ ├── p06_reloading_modules.ipynb
│ │ ├── p07_make_directory_or_zip_runnable_as_main_script.ipynb
│ │ ├── p08_read_datafile_within_package.ipynb
│ │ ├── p09_add_directories_to_sys_path.ipynb
│ │ ├── p10_import_modules_using_name_given_in_string.ipynb
│ │ ├── p11_load_modules_from_remote_machine_by_hooks.ipynb
│ │ ├── p12_patching_modules_on_import.ipynb
│ │ ├── p13_installing_packages_just_for_yourself.ipynb
│ │ ├── p14_creating_new_python_environment.ipynb
│ │ └── p15_distributing_packages.ipynb
│ ├── 第十章:模块与包.ipynb
│ ├── 第四章:迭代器与生成器/
│ │ ├── p01_manually_consuming_iterator.ipynb
│ │ ├── p02_delegating_iteration.ipynb
│ │ ├── p03_create_new_iteration_with_generators.ipynb
│ │ ├── p04_implement_iterator_protocol.ipynb
│ │ ├── p05_iterating_in_reverse.ipynb
│ │ ├── p06_define_generator_func_with_extra_state.ipynb
│ │ ├── p07_taking_slice_of_iterator.ipynb
│ │ ├── p08_skip_first_part_of_iterable.ipynb
│ │ ├── p09_iterate_over_combination_or_permutation.ipynb
│ │ ├── p10_iterate_over_index_value_pairs_of_sequence.ipynb
│ │ ├── p11_iterate_over_multiple_sequences_simultaneously.ipynb
│ │ ├── p12_iterate_on_items_in_separate_containers.ipynb
│ │ ├── p13_create_data_processing_pipelines.ipynb
│ │ ├── p14_flattening_nested_sequence.ipynb
│ │ ├── p15_iterate_in_sorted_order_over_merged_sorted_iterables.ipynb
│ │ └── p16_replace_infinite_while_loops_with_iterator.ipynb
│ └── 第四章:迭代器与生成器.ipynb
├── requirements_.txt
└── source/
├── aboutme.rst
├── c01/
│ ├── p01_unpack_sequence_into_separate_variables.rst
│ ├── p02_unpack_elements_from_iterables.rst
│ ├── p03_keep_last_n_items.rst
│ ├── p04_find_largest_or_smallest_n_items.rst
│ ├── p05_implement_a_priority_queue.rst
│ ├── p06_map_keys_to_multiple_values_in_dict.rst
│ ├── p07_keep_dict_in_order.rst
│ ├── p08_calculating_with_dict.rst
│ ├── p09_find_commonalities_in_dicts.rst
│ ├── p10_remove_duplicates_from_seq_order.rst
│ ├── p11_naming_slice.rst
│ ├── p12_determine_most_freqently_items_in_seq.rst
│ ├── p13_sort_list_of_dicts_by_key.rst
│ ├── p14_sort_objects_without_compare_support.rst
│ ├── p15_group_records_based_on_field.rst
│ ├── p16_filter_sequence_elements.rst
│ ├── p17_extract_subset_of_dict.rst
│ ├── p18_map_names_to_sequence_elements.rst
│ ├── p19_transform_and_reduce_data_same_time.rst
│ └── p20_combine_multiple_map_to_single_map.rst
├── c02/
│ ├── p01_split_string_on_multiple_delimiters.rst
│ ├── p02_match_text_at_start_end.rst
│ ├── p03_match_strings_with_shell_wildcard.rst
│ ├── p04_match_and_search_text.rst
│ ├── p05_search_and_replace_text.rst
│ ├── p06_search_replace_case_insensitive.rst
│ ├── p07_specify_regexp_for_shortest_match.rst
│ ├── p08_regexp_for_multiline_partterns.rst
│ ├── p09_normalize_unicode_text_to_regexp.rst
│ ├── p10_work_with_unicode_in_regexp.rst
│ ├── p11_strip_unwanted_characters.rst
│ ├── p12_sanitizing_clean_up_text.rst
│ ├── p13_aligning_text_strings.rst
│ ├── p14_combine_and_concatenate_strings.rst
│ ├── p15_interpolating_variables_in_strings.rst
│ ├── p16_reformat_text_to_fixed_number_columns.rst
│ ├── p17_handle_html_xml_in_text.rst
│ ├── p18_tokenizing_text.rst
│ ├── p19_writing_recursive_descent_parser.rst
│ └── p20_perform_text_operations_on_byte_string.rst
├── c03/
│ ├── p01_round_number.rst
│ ├── p02_accurate_decimal_calculations.rst
│ ├── p03_format_numbers_for_output.rst
│ ├── p04_binary_octal_hexadecimal_int.rst
│ ├── p05_pack_unpack_large_int_from_bytes.rst
│ ├── p06_complex_math.rst
│ ├── p07_infinity_and_nan.rst
│ ├── p08_calculating_with_fractions.rst
│ ├── p09_calculating_with_large_num_arrays.rst
│ ├── p10_matrix_and_linear_algebra_calculation.rst
│ ├── p11_pick_things_at_random.rst
│ ├── p12_convert_days_to_seconds_and_others.rst
│ ├── p13_determine_last_friday_date.rst
│ ├── p14_date_range_for_current_month.rst
│ ├── p15_convert_strings_into_datetimes.rst
│ └── p16_manipulate_dates_involving_timezone.rst
├── c04/
│ ├── p01_manually_consuming_iterator.rst
│ ├── p02_delegating_iteration.rst
│ ├── p03_create_new_iteration_with_generators.rst
│ ├── p04_implement_iterator_protocol.rst
│ ├── p05_iterating_in_reverse.rst
│ ├── p06_define_generator_func_with_extra_state.rst
│ ├── p07_taking_slice_of_iterator.rst
│ ├── p08_skip_first_part_of_iterable.rst
│ ├── p09_iterate_over_combination_or_permutation.rst
│ ├── p10_iterate_over_index_value_pairs_of_sequence.rst
│ ├── p11_iterate_over_multiple_sequences_simultaneously.rst
│ ├── p12_iterate_on_items_in_separate_containers.rst
│ ├── p13_create_data_processing_pipelines.rst
│ ├── p14_flattening_nested_sequence.rst
│ ├── p15_iterate_in_sorted_order_over_merged_sorted_iterables.rst
│ └── p16_replace_infinite_while_loops_with_iterator.rst
├── c05/
│ ├── p01_read_write_text_data.rst
│ ├── p02_printing_to_file.rst
│ ├── p03_print_with_different_separator_or_line_ending.rst
│ ├── p04_read_write_binary_data.rst
│ ├── p05_write_to_file_not_exist.rst
│ ├── p06_io_operations_on_string.rst
│ ├── p07_read_write_compressed_datafiles.rst
│ ├── p08_iterate_over_fixed_sized_records.rst
│ ├── p09_read_binary_data_into_mutable_buffer.rst
│ ├── p10_memory_mapping_binary_files.rst
│ ├── p11_manipulating_pathnames.rst
│ ├── p12_test_for_the_existence_of_file.rst
│ ├── p13_get_directory_listing.rst
│ ├── p14_bypassing_filename_encoding.rst
│ ├── p15_printing_bad_filenames.rst
│ ├── p16_add_change_encoding_of_already_open_file.rst
│ ├── p17_write_bytes_to_text_file.rst
│ ├── p18_wrap_existing_file_descriptor_as_file_object.rst
│ ├── p19_make_temporary_files_and_directories.rst
│ ├── p20_communicating_with_serial_ports.rst
│ └── p21_serializing_python_objects.rst
├── c06/
│ ├── p01_read_write_csv_data.rst
│ ├── p02_read-write_json_data.rst
│ ├── p03_parse_simple_xml_data.rst
│ ├── p04_parse_huge_xml_files_incrementally.rst
│ ├── p05_turning_dictionary_into_xml.rst
│ ├── p06_parse_modify_rewrite_xml.rst
│ ├── p07_parse_xml_documents_with_namespaces.rst
│ ├── p08_interact_with_relational_database.rst
│ ├── p09_decode_encode_hexadecimal_digits.rst
│ ├── p10_decode_encode_base64.rst
│ ├── p11_read_write_binary_arrays_of_structures.rst
│ ├── p12_read_nested_and_variable_sized_binary_structures.rst
│ └── p13_summarizing_and_perform_statistics.rst
├── c07/
│ ├── p01_functions_that_accept_any_number_arguments.rst
│ ├── p02_functions_that_only_accept_keyword_arguments.rst
│ ├── p03_attach_informatinal_matadata_to_function_arguments.rst
│ ├── p04_return_multiple_values_from_function.rst
│ ├── p05_define_functions_with_default_arguments.rst
│ ├── p06_define_anonymous_or_inline_functions.rst
│ ├── p07_capturing_variables_in_anonymous_functions.rst
│ ├── p08_make_callable_with_fewer_arguments.rst
│ ├── p09_replace_single_method_classes_with_functions.rst
│ ├── p10_carry_extra_state_with_callback_functions.rst
│ ├── p11_inline_callback_functions.rst
│ └── p12_access_variables_defined_inside_closure.rst
├── c08/
│ ├── p01_change_string_representation_of_instances.rst
│ ├── p02_customizing_string_formatting.rst
│ ├── p03_make_objects_support_context_management_protocol.rst
│ ├── p04_save_memory_when_create_large_number_instances.rst
│ ├── p05_encapsulating_names_in_class.rst
│ ├── p06_create_managed_attributes.rst
│ ├── p07_calling_method_on_parent_class.rst
│ ├── p08_extending_property_in_subclass.rst
│ ├── p09_create_new_kind_of_class_or_instance_attribute.rst
│ ├── p10_using_lazily_computed_properties.rst
│ ├── p11_simplify_initialization_of_data_structure.rst
│ ├── p12_define_interface_or_abstract_base_class.rst
│ ├── p13_implementing_data_model_or_type_system.rst
│ ├── p14_implementing_custom_containers.rst
│ ├── p15_delegating_attribute_access.rst
│ ├── p16_define_more_than_one_constructor_in_class.rst
│ ├── p17_create_instance_without_invoking_init_method.rst
│ ├── p18_extending_classes_with_mixins.rst
│ ├── p19_implements_stateful_objects_or_state_machines.rst
│ ├── p20_call_method_on_object_by_string_name.rst
│ ├── p21_implementing_visitor_pattern.rst
│ ├── p22_implementing_visitor_pattern_without_recursion.rst
│ ├── p23_managing_memory_in_cyclic_data_structures.rst
│ ├── p24_making_classes_support_comparison_operations.rst
│ └── p25_creating_cached_instances.rst
├── c09/
│ ├── p01_put_wrapper_around_function.rst
│ ├── p02_preserve_function_metadata_when_write_decorators.rst
│ ├── p03_unwrapping_decorator.rst
│ ├── p04_define_decorator_that_takes_arguments.rst
│ ├── p05_define_decorator_with_user_adjustable_attributes.rst
│ ├── p06_define_decorator_that_takes_optional_argument.rst
│ ├── p07_enforcing_type_check_on_function_using_decorator.rst
│ ├── p08_define_decorators_as_part_of_class.rst
│ ├── p09_define_decorators_as_classes.rst
│ ├── p10_apply_decorators_to_class_and_static_methods.rst
│ ├── p11_write_decorators_that_add_arguments_to_functions.rst
│ ├── p12_using_decorators_to_patch_class_definitions.rst
│ ├── p13_using_mataclass_to_control_instance_creation.rst
│ ├── p14_capture_class_attribute_definition_order.rst
│ ├── p15_define_metaclass_that_takes_optional_arguments.rst
│ ├── p16_enforce_argument_signature_on_args_kwargs.rst
│ ├── p17_enforce_coding_conventions_in_classes.rst
│ ├── p18_define_classes_programmatically.rst
│ ├── p19_initializing_class_members_at_definition_time.rst
│ ├── p20_implement_multiple_dispatch_with_function_annotations.rst
│ ├── p21_avoid_repetitive_property_methods.rst
│ ├── p22_define_context_managers_the_easy_way.rst
│ ├── p23_executing_code_with_local_side_effects.rst
│ ├── p24_parse_and_analyzing_python_source.rst
│ └── p25_disassembling_python_byte_code.rst
├── c10/
│ ├── p01_make_hierarchical_package_of_modules.rst
│ ├── p02_control_the_import_of_everything.rst
│ ├── p03_import_submodules_by_relative_names.rst
│ ├── p04_split_module_into_multiple_files.rst
│ ├── p05_separate_directories_import_by_namespace.rst
│ ├── p06_reloading_modules.rst
│ ├── p07_make_directory_or_zip_runnable_as_main_script.rst
│ ├── p08_read_datafile_within_package.rst
│ ├── p09_add_directories_to_sys_path.rst
│ ├── p10_import_modules_using_name_given_in_string.rst
│ ├── p11_load_modules_from_remote_machine_by_hooks.rst
│ ├── p12_patching_modules_on_import.rst
│ ├── p13_installing_packages_just_for_yourself.rst
│ ├── p14_creating_new_python_environment.rst
│ └── p15_distributing_packages.rst
├── c11/
│ ├── p01_interact_with_http_services_as_client.rst
│ ├── p02_creating_tcp_server.rst
│ ├── p03_creating_udp_server.rst
│ ├── p04_generate_range_of_ip_addresses_from_cidr_address.rst
│ ├── p05_creating_simple_rest_based_interface.rst
│ ├── p06_implement_simple_remote_procedure_call_with_xml_rpc.rst
│ ├── p07_communicate_simply_between_interpreters.rst
│ ├── p08_implementing_remote_procedure_calls.rst
│ ├── p09_authenticating_clients_simply.rst
│ ├── p10_add_ssl_to_network_services.rst
│ ├── p11_pass_socket_file_descriptor_between_processes.rst
│ ├── p12_understanding_event_driven_io.rst
│ └── p13_sending_receiving_large_arrays.rst
├── c12/
│ ├── p01_start_stop_thread.rst
│ ├── p02_determining_if_thread_has_started.rst
│ ├── p03_communicating_between_threads.rst
│ ├── p04_locking_critical_sections.rst
│ ├── p05_locking_with_deadlock_avoidance.rst
│ ├── p06_storing_thread_specific_state.rst
│ ├── p07_creating_thread_pool.rst
│ ├── p08_perform_simple_parallel_programming.rst
│ ├── p09_dealing_with_gil_stop_worring_about_it.rst
│ ├── p10_defining_an_actor_task.rst
│ ├── p11_implement_publish_subscribe_messaging.rst
│ ├── p12_using_generators_as_alternative_to_threads.rst
│ ├── p13_polling_multiple_thread_queues.rst
│ └── p14_launching_daemon_process_on_unix.rst
├── c13/
│ ├── p01_accept_input_via_redirect_pips_or_input_files.rst
│ ├── p02_terminate_program_with_an_error_message.rst
│ ├── p03_parsing_command_line_options.rst
│ ├── p04_prompt_for_password_at_runtime.rst
│ ├── p05_getting_terminal_size.rst
│ ├── p06_executing_external_command_and_get_its_output.rst
│ ├── p07_copy_move_files_and_directories.rst
│ ├── p08_creating_and_unpacking_archives.rst
│ ├── p09_find_files_by_name.rst
│ ├── p10_read_configuration_files.rst
│ ├── p11_add_logging_to_simple_scripts.rst
│ ├── p12_add_logging_to_libraries.rst
│ ├── p13_making_stopwatch_timer.rst
│ ├── p14_putting_limits_on_memory_and_cpu_usage.rst
│ └── p15_luanch_a_web_browser.rst
├── c14/
│ ├── p01_testing_output_sent_to_stdout.rst
│ ├── p02_patching_objects_in_unit_tests.rst
│ ├── p03_testing_for_exceptional_conditions_in_unit_tests.rst
│ ├── p04_logging_test_output_to_file.rst
│ ├── p05_skip_or_anticipate_test_failures.rst
│ ├── p06_handle_multiple_exceptions.rst
│ ├── p07_catching_all_exceptions.rst
│ ├── p08_creating_custom_exceptions.rst
│ ├── p09_raise_exception_in_response_to_another_exception.rst
│ ├── p10_reraising_the_last_exception.rst
│ ├── p11_issuing_warning_messages.rst
│ ├── p12_debugging_basic_program_crashes.rst
│ ├── p13_profiling_and_timing_your_program.rst
│ └── p14_make_your_program_run_faster.rst
├── c15/
│ ├── p01_access_ccode_using_ctypes.rst
│ ├── p02_write_simple_c_extension_module.rst
│ ├── p03_write_extension_function_operate_on_arrays.rst
│ ├── p04_manage_opaque_pointers_in_c_extension_modules.rst
│ ├── p05_define_and_export_c_api_from_extension_modules.rst
│ ├── p06_calling_python_from_c.rst
│ ├── p07_release_the_gil_in_c_extensions.rst
│ ├── p08_mix_threads_from_c_and_python.rst
│ ├── p09_wrap_c_code_with_swig.rst
│ ├── p10_wrap_existing_c_code_with_cython.rst
│ ├── p11_use_cython_to_write_high_performance_array_operation.rst
│ ├── p12_turning_function_pointer_into_callable.rst
│ ├── p13_pass_null_terminated_string_to_c_libraries.rst
│ ├── p14_pass_unicode_strings_to_c_libraries.rst
│ ├── p15_converting_c_string_to_python.rst
│ ├── p16_work_with_c_strings_of_dubious_encoding.rst
│ ├── p17_pass_filenames_to_c_extensions.rst
│ ├── p18_pass_open_files_to_c_extensions.rst
│ ├── p19_read_file_like_objects_from_c.rst
│ ├── p20_consuming_an_iterable_from_c.rst
│ └── p21_diagnosing_segmentation_faults.rst
├── chapters/
│ ├── p01_data_structures_algorithms.rst
│ ├── p02_strings_and_text.rst
│ ├── p03_numbers_dates_times.rst
│ ├── p04_iterators_and_generators.rst
│ ├── p05_files_and_io.rst
│ ├── p06_data_encoding_and_process.rst
│ ├── p07_functions.rst
│ ├── p08_classes_and_objects.rst
│ ├── p09_meta_programming.rst
│ ├── p10_modules_and_packages.rst
│ ├── p11_network_and_web_program.rst
│ ├── p12_concurrency.rst
│ ├── p13_utility_script_and_system_manage.rst
│ ├── p14_test_debug_and_exceptions.rst
│ ├── p15_c_extensions.rst
│ └── p16_appendix.rst
├── conf.py
├── copyright.rst
├── index.rst
├── preface.rst
└── roadmap.rst
SYMBOL INDEX (848 symbols across 167 files)
FILE: cookbook/c01/p03_nitem.py
function search (line 10) | def search(lines, pattern, history=5):
FILE: cookbook/c01/p04_nlargest.py
function main (line 10) | def main():
FILE: cookbook/c01/p05_priority_queue.py
class PriorityQueue (line 10) | class PriorityQueue:
method __init__ (line 11) | def __init__(self):
method push (line 15) | def push(self, item, priority):
method pop (line 19) | def pop(self):
FILE: cookbook/c01/p06_multidict.py
function multi_dict (line 11) | def multi_dict():
FILE: cookbook/c01/p08_calculate_dict.py
function calc_dict (line 9) | def calc_dict():
FILE: cookbook/c01/p09_dict_common.py
function dict_commonality (line 9) | def dict_commonality():
FILE: cookbook/c01/p10_remove_duplicate.py
function dedupe (line 9) | def dedupe(items):
function dedupe2 (line 18) | def dedupe2(items, key=None):
function remove_dup (line 28) | def remove_dup():
FILE: cookbook/c01/p11_naming_slice.py
function name_slice (line 9) | def name_slice():
FILE: cookbook/c01/p12_mostfreq_items.py
function most_freqency (line 9) | def most_freqency():
FILE: cookbook/c01/p13_sort_dictlist.py
function sort_dictlist (line 9) | def sort_dictlist():
FILE: cookbook/c01/p14_sort_nocompare.py
class User (line 9) | class User:
method __init__ (line 10) | def __init__(self, user_id):
method __repr__ (line 13) | def __repr__(self):
function sort_notcompare (line 17) | def sort_notcompare():
FILE: cookbook/c01/p15_group.py
function group_iter (line 11) | def group_iter():
FILE: cookbook/c01/p16_filter.py
function cb_filter (line 10) | def cb_filter():
FILE: cookbook/c01/p17_subdict.py
function sub_dict (line 9) | def sub_dict():
FILE: cookbook/c01/p18_nameseq.py
function name_seq (line 10) | def name_seq():
function compute_cost (line 21) | def compute_cost(records):
function compute_cost2 (line 28) | def compute_cost2(records):
function dict_to_stock (line 45) | def dict_to_stock(s):
function default_stock (line 48) | def default_stock():
FILE: cookbook/c01/p19_trans_reduce.py
function trans_reduce (line 10) | def trans_reduce():
FILE: cookbook/c01/p20_combine_map.py
function combine_map (line 11) | def combine_map():
FILE: cookbook/c02/p01_splitstr.py
function split_str (line 10) | def split_str():
FILE: cookbook/c02/p02_str_start.py
function start_end (line 12) | def start_end():
function read_data (line 39) | def read_data(name):
FILE: cookbook/c02/p03_unix_match.py
function unix_match (line 10) | def unix_match():
FILE: cookbook/c02/p04_match_search.py
function match_search (line 10) | def match_search():
FILE: cookbook/c02/p05_search_replace.py
function change_date (line 11) | def change_date(m):
function search_replace (line 16) | def search_replace():
FILE: cookbook/c02/p06_case_insensitive.py
function matchcase (line 10) | def matchcase(word):
function case_insens (line 23) | def case_insens():
FILE: cookbook/c02/p07_shortest_match.py
function short_match (line 11) | def short_match():
FILE: cookbook/c02/p08_multiline_match.py
function multiline_match (line 10) | def multiline_match():
FILE: cookbook/c02/p09_normal_unicode.py
function nor_unicode (line 10) | def nor_unicode():
FILE: cookbook/c02/p10_re_unicode.py
function re_unicode (line 10) | def re_unicode():
FILE: cookbook/c02/p11_strip.py
function strip_str (line 10) | def strip_str():
FILE: cookbook/c02/p12_translate.py
function clean_spaces (line 11) | def clean_spaces(s):
function translate_str (line 19) | def translate_str():
FILE: cookbook/c02/p13_align_str.py
function align_str (line 9) | def align_str():
FILE: cookbook/c02/p14_join_str.py
function combine (line 9) | def combine(source, maxsize):
function sample (line 22) | def sample():
function join_str (line 29) | def join_str():
FILE: cookbook/c02/p15_var_string.py
class Info (line 9) | class Info:
method __init__ (line 10) | def __init__(self, name, n):
class SafeSub (line 15) | class SafeSub(dict):
method __missing__ (line 17) | def __missing__(self, key):
function sub (line 21) | def sub(text):
function var_str (line 24) | def var_str():
FILE: cookbook/c02/p16_textwrap.py
function reformat_width (line 11) | def reformat_width():
FILE: cookbook/c02/p17_html_xml.py
function html_xml (line 10) | def html_xml():
FILE: cookbook/c02/p18_tokenize.py
function tokenize_str (line 11) | def tokenize_str():
function generate_tokens (line 70) | def generate_tokens(pat, text):
FILE: cookbook/c02/p19_descent_parser.py
function generate_tokens (line 26) | def generate_tokens(text):
class ExpressionEvaluator (line 35) | class ExpressionEvaluator:
method parse (line 44) | def parse(self, text):
method _advance (line 51) | def _advance(self):
method _accept (line 55) | def _accept(self, toktype):
method _expect (line 63) | def _expect(self, toktype):
method expr (line 69) | def expr(self):
method term (line 81) | def term(self):
method factor (line 93) | def factor(self):
function descent_parser (line 105) | def descent_parser():
FILE: cookbook/c02/p20_byte_str.py
function byte_str (line 11) | def byte_str():
FILE: cookbook/c03/p01_round.py
function round_num (line 9) | def round_num():
FILE: cookbook/c03/p02_accurate_decimal.py
function acc_deciamal (line 12) | def acc_deciamal():
FILE: cookbook/c03/p03_format_number.py
function format_number (line 9) | def format_number():
FILE: cookbook/c03/p04_bin_octal.py
function bin_octal (line 9) | def bin_octal():
FILE: cookbook/c03/p05_int_bytes.py
function int_bytes (line 9) | def int_bytes():
FILE: cookbook/c03/p06_complex.py
function complex_math (line 10) | def complex_math():
FILE: cookbook/c03/p07_inf_nan.py
function inf_nan (line 9) | def inf_nan():
FILE: cookbook/c03/p08_fraction.py
function frac (line 10) | def frac():
FILE: cookbook/c03/p09_array_numpy.py
function array_numpy (line 10) | def array_numpy():
function f (line 50) | def f(x):
FILE: cookbook/c03/p10_matrix_linear.py
function matrix_linear (line 11) | def matrix_linear():
FILE: cookbook/c03/p11_random_num.py
function random_num (line 10) | def random_num():
FILE: cookbook/c03/p12_datatime.py
function date_time (line 12) | def date_time():
FILE: cookbook/c03/p13_last_friday.py
function get_previous_byday (line 15) | def get_previous_byday(dayname, start_date=None):
function last_friday (line 27) | def last_friday():
FILE: cookbook/c03/p14_month_range.py
function get_month_range (line 11) | def get_month_range(start_date=None):
function date_range (line 19) | def date_range(start, stop, step):
function month_range (line 25) | def month_range():
FILE: cookbook/c03/p15_str_datetime.py
function str_datetime (line 10) | def str_datetime():
function parse_ymd (line 22) | def parse_ymd(s):
FILE: cookbook/c03/p16_timezone.py
function tz_local (line 12) | def tz_local():
FILE: cookbook/c04/p01_manual_iterator.py
function manual_iter (line 9) | def manual_iter():
function manual_iter2 (line 18) | def manual_iter2():
FILE: cookbook/c04/p02_delegate_iter.py
class Node (line 9) | class Node:
method __init__ (line 10) | def __init__(self, value):
method __repr__ (line 14) | def __repr__(self):
method add_child (line 17) | def add_child(self, node):
method __iter__ (line 20) | def __iter__(self):
FILE: cookbook/c04/p03_generator_pattern.py
function frange (line 9) | def frange(start, stop, increment):
function countdown (line 16) | def countdown(n):
function gen_pattern (line 24) | def gen_pattern():
FILE: cookbook/c04/p04_iterator_protocol.py
class Node (line 9) | class Node:
method __init__ (line 10) | def __init__(self, value):
method __repr__ (line 14) | def __repr__(self):
method add_child (line 17) | def add_child(self, node):
method __iter__ (line 20) | def __iter__(self):
method depth_first (line 23) | def depth_first(self):
class Node2 (line 29) | class Node2:
method __init__ (line 30) | def __init__(self, value):
method __repr__ (line 34) | def __repr__(self):
method add_child (line 37) | def add_child(self, node):
method __iter__ (line 40) | def __iter__(self):
method depth_first (line 43) | def depth_first(self):
class DepthFirstIterator (line 47) | class DepthFirstIterator(object):
method __init__ (line 52) | def __init__(self, start_node):
method __iter__ (line 57) | def __iter__(self):
method __next__ (line 60) | def __next__(self):
FILE: cookbook/c04/p05_reverse_iterate.py
function reverse_iterate (line 9) | def reverse_iterate():
class Countdown (line 27) | class Countdown:
method __init__ (line 28) | def __init__(self, start):
method __iter__ (line 32) | def __iter__(self):
method __reversed__ (line 39) | def __reversed__(self):
FILE: cookbook/c04/p06_generator_extrastate.py
class linehistory (line 10) | class linehistory:
method __init__ (line 11) | def __init__(self, lines, histlen=3):
method __iter__ (line 15) | def __iter__(self):
method clear (line 20) | def clear(self):
function gen_extrastate (line 24) | def gen_extrastate():
FILE: cookbook/c04/p07_iterator_slice.py
function count (line 10) | def count(n):
function iter_slice (line 16) | def iter_slice():
FILE: cookbook/c04/p08_skip_iterable.py
function skip_iter (line 11) | def skip_iter():
FILE: cookbook/c04/p09_iter_permutation.py
function iter_permutation (line 12) | def iter_permutation():
FILE: cookbook/c04/p10_iterate_index.py
function iterate_index (line 10) | def iterate_index():
function parse_data (line 25) | def parse_data(filename):
function word_lines (line 36) | def word_lines():
FILE: cookbook/c04/p11_iterate_simultaneous.py
function iterate_simul (line 10) | def iterate_simul():
FILE: cookbook/c04/p12_iterate_separate.py
function iter_separate (line 10) | def iter_separate():
FILE: cookbook/c04/p13_process_pipline.py
function gen_find (line 15) | def gen_find(filepat, top):
function gen_opener (line 24) | def gen_opener(filenames):
function gen_concatenate (line 40) | def gen_concatenate(iterators):
function gen_grep (line 48) | def gen_grep(pattern, lines):
function process_pipline (line 58) | def process_pipline():
FILE: cookbook/c04/p14_flatten_sequence.py
function flatten (line 10) | def flatten(items, ignore_types=(str, bytes)):
function flatten_seq (line 18) | def flatten_seq():
FILE: cookbook/c04/p15_merge_sorted.py
function merge_sorted (line 10) | def merge_sorted():
FILE: cookbook/c04/p16_iterate_while.py
function process_data (line 10) | def process_data():
function reader (line 14) | def reader(s, size):
function reader2 (line 22) | def reader2(s, size):
function iterate_while (line 27) | def iterate_while():
FILE: cookbook/c05/p01_rw_text.py
function rw_text (line 8) | def rw_text():
FILE: cookbook/c05/p02_print_tofile.py
function print_tofile (line 9) | def print_tofile():
FILE: cookbook/c05/p03_print_sepend.py
function print_sepend (line 8) | def print_sepend():
FILE: cookbook/c05/p04_rw_binary.py
function rw_binary (line 9) | def rw_binary():
FILE: cookbook/c05/p05_write_notexist.py
function write_noexist (line 9) | def write_noexist():
FILE: cookbook/c05/p06_string_io.py
function string_io (line 10) | def string_io():
FILE: cookbook/c05/p07_gzip_bz2.py
function gzip_bz2 (line 11) | def gzip_bz2():
FILE: cookbook/c05/p08_iterate_fixedsize.py
function iterate_fixed (line 10) | def iterate_fixed():
FILE: cookbook/c05/p09_read_tobuffer.py
function read_into_buffer (line 10) | def read_into_buffer(filename):
function read_tobuffer (line 17) | def read_tobuffer():
FILE: cookbook/c05/p10_memery_mapping.py
function memory_map (line 11) | def memory_map(filename, access=mmap.ACCESS_WRITE):
function mem_mapping (line 17) | def mem_mapping():
FILE: cookbook/c05/p11_pathnames.py
function path_names (line 10) | def path_names():
FILE: cookbook/c05/p12_file_existence.py
function file_existence (line 11) | def file_existence():
FILE: cookbook/c05/p13_dir_listfile.py
function dir_listfile (line 13) | def dir_listfile():
FILE: cookbook/c05/p14_bypass_encode.py
function bypass_encoding (line 10) | def bypass_encoding():
FILE: cookbook/c05/p15_print_badfile.py
function bad_filename (line 11) | def bad_filename(filename):
function bad_filename2 (line 15) | def bad_filename2(filename):
function print_badfile (line 21) | def print_badfile(filename):
FILE: cookbook/c05/p16_change_opencode.py
function change_open_encode (line 12) | def change_open_encode():
FILE: cookbook/c05/p17_bytes_tofile.py
function bytes_tofile (line 10) | def bytes_tofile():
FILE: cookbook/c05/p18_file_descriptor.py
function file_descriptor (line 12) | def file_descriptor():
function echo_client (line 26) | def echo_client(client_sock, addr):
function echo_server (line 44) | def echo_server(address):
FILE: cookbook/c05/p19_temp_file.py
function temp_file (line 13) | def temp_file():
FILE: cookbook/c05/p20_serial_ports.py
function serial_posts (line 10) | def serial_posts():
FILE: cookbook/c05/p21_serialize_object.py
function serailize_object (line 10) | def serailize_object():
FILE: cookbook/c06/p01_rw_csv.py
function rw_csv (line 11) | def rw_csv():
FILE: cookbook/c06/p02_rw_json.py
class JSONObject (line 11) | class JSONObject:
method __init__ (line 12) | def __init__(self, d):
class Point (line 16) | class Point:
method __init__ (line 17) | def __init__(self, x, y):
function serialize_instance (line 22) | def serialize_instance(obj):
function unserialize_object (line 28) | def unserialize_object(d):
function rw_json (line 45) | def rw_json():
FILE: cookbook/c06/p03_simple_xml.py
function simple_xml (line 11) | def simple_xml():
FILE: cookbook/c06/p04_huge_xml.py
function parse_and_remove (line 12) | def parse_and_remove(filename, path):
function huge_xml (line 35) | def huge_xml():
FILE: cookbook/c06/p05_dict_toxml.py
function dict_to_xml (line 11) | def dict_to_xml(tag, d):
FILE: cookbook/c06/p06_rw_xml.py
function rw_xml (line 10) | def rw_xml():
FILE: cookbook/c06/p07_namespace_xml.py
class XMLNamespaces (line 9) | class XMLNamespaces:
method __init__ (line 10) | def __init__(self, **kwargs):
method register (line 15) | def register(self, name, uri):
method __call__ (line 18) | def __call__(self, path):
FILE: cookbook/c06/p08_database.py
function db_operation (line 11) | def db_operation():
FILE: cookbook/c06/p09_codec_hex.py
function codec_hex (line 11) | def codec_hex():
FILE: cookbook/c06/p10_codec_base64.py
function codec_base64 (line 10) | def codec_base64():
FILE: cookbook/c06/p11_rw_barray.py
function write_records (line 11) | def write_records(records, format, f):
function read_records (line 20) | def read_records(format, f):
function unpack_records (line 26) | def unpack_records(format, data):
FILE: cookbook/c06/p12_var_binary.py
function write_polys (line 16) | def write_polys(filename, polys):
function read_polys (line 36) | def read_polys(filename):
FILE: cookbook/c07/p02_keyarg_only.py
function recv (line 9) | def recv(maxsize, *, block):
function minimum (line 17) | def minimum(*values, clip=None):
FILE: cookbook/c07/p03_func_annotate.py
function add (line 8) | def add(x:int, y:int) -> int:
FILE: cookbook/c07/p05_default_argument.py
function spam (line 8) | def spam(a, b=42):
function spam (line 16) | def spam(a, b=_no_value):
FILE: cookbook/c07/p08_partial.py
function spam (line 13) | def spam(a, b, c, d):
function output_result (line 17) | def output_result(result, log=None):
function add (line 23) | def add(x, y):
class EchoHandler (line 27) | class EchoHandler(StreamRequestHandler):
method __init__ (line 30) | def __init__(self, *args, ack, **kwargs):
method handle (line 34) | def handle(self):
FILE: cookbook/c07/p09_class_to_func.py
class UrlTemplate (line 11) | class UrlTemplate:
method __init__ (line 12) | def __init__(self, template):
method open (line 15) | def open(self, **kwargs):
function urltemplate (line 25) | def urltemplate(template):
FILE: cookbook/c07/p10_callback.py
function apply_async (line 9) | def apply_async(func, args, *, callback):
function add (line 17) | def add(x, y):
class ResultHandler (line 22) | class ResultHandler:
method __init__ (line 24) | def __init__(self):
method handler (line 27) | def handler(self, result):
function make_handler (line 37) | def make_handler():
function make_handler (line 51) | def make_handler():
FILE: cookbook/c07/p11_inline_callback.py
function apply_async (line 11) | def apply_async(func, args, *, callback):
class Async (line 19) | class Async:
method __init__ (line 20) | def __init__(self, func, args):
function inlined_async (line 25) | def inlined_async(func):
function add (line 48) | def add(x, y):
function test (line 53) | def test():
FILE: cookbook/c07/p12_closure_access.py
function sample (line 9) | def sample():
class ClosureInstance (line 34) | class ClosureInstance:
method __init__ (line 35) | def __init__(self, locals=None):
method __len__ (line 43) | def __len__(self):
function Stack (line 47) | def Stack():
FILE: cookbook/c08/p01_str_represent.py
class Pair (line 9) | class Pair:
method __init__ (line 10) | def __init__(self, x, y):
method __repr__ (line 14) | def __repr__(self):
method __str__ (line 17) | def __str__(self):
FILE: cookbook/c08/p02_custom_format.py
class Date (line 14) | class Date:
method __init__ (line 15) | def __init__(self, year, month, day):
method __format__ (line 20) | def __format__(self, code):
FILE: cookbook/c08/p03_context_protocol.py
class LazyConnection (line 11) | class LazyConnection:
method __init__ (line 12) | def __init__(self, address, family=AF_INET, type=SOCK_STREAM):
method __enter__ (line 18) | def __enter__(self):
method __exit__ (line 25) | def __exit__(self, exc_ty, exc_val, tb):
class LazyConnection2 (line 44) | class LazyConnection2:
method __init__ (line 45) | def __init__(self, address, family=AF_INET, type=SOCK_STREAM):
method __enter__ (line 51) | def __enter__(self):
method __exit__ (line 57) | def __exit__(self, exc_ty, exc_val, tb):
FILE: cookbook/c08/p04_slots.py
class Date (line 9) | class Date:
method __init__ (line 12) | def __init__(self, year, month, day):
FILE: cookbook/c08/p05_encapsulate_name.py
class A (line 9) | class A:
method __init__ (line 10) | def __init__(self):
method public_method (line 14) | def public_method(self):
method _internal_method (line 20) | def _internal_method(self):
class B (line 24) | class B:
method __init__ (line 25) | def __init__(self):
method __private_method (line 28) | def __private_method(self):
method public_method (line 31) | def public_method(self):
class C (line 36) | class C(B):
method __init__ (line 37) | def __init__(self):
method __private_method (line 42) | def __private_method(self):
FILE: cookbook/c08/p06_managed_attribute.py
class Person (line 10) | class Person:
method __init__ (line 11) | def __init__(self, first_name):
method first_name (line 16) | def first_name(self):
method first_name (line 21) | def first_name(self, value):
method first_name (line 28) | def first_name(self):
class Person1 (line 38) | class Person1:
method __init__ (line 39) | def __init__(self, first_name):
method get_first_name (line 43) | def get_first_name(self):
method set_first_name (line 47) | def set_first_name(self, value):
method del_first_name (line 53) | def del_first_name(self):
class Circle (line 65) | class Circle:
method __init__ (line 68) | def __init__(self, radius):
method diameter (line 72) | def diameter(self):
method perimeter (line 76) | def perimeter(self):
method area (line 80) | def area(self):
FILE: cookbook/c08/p07_super_method.py
class A (line 9) | class A:
method spam (line 10) | def spam(self):
class B (line 14) | class B(A):
method spam (line 15) | def spam(self):
class A1 (line 20) | class A1:
method __init__ (line 21) | def __init__(self):
class B1 (line 25) | class B1(A1):
method __init__ (line 26) | def __init__(self):
class Proxy (line 31) | class Proxy():
method __init__ (line 32) | def __init__(self, obj):
method __getattr__ (line 36) | def __getattr__(self, name):
method __setattr__ (line 40) | def __setattr__(self, name, value):
class Base (line 47) | class Base:
method __init__ (line 48) | def __init__(self):
class AA (line 52) | class AA(Base):
method __init__ (line 53) | def __init__(self):
class BB (line 58) | class BB(Base):
method __init__ (line 59) | def __init__(self):
class CC (line 64) | class CC(AA, BB):
method __init__ (line 65) | def __init__(self):
class A3 (line 74) | class A3:
method spam (line 75) | def spam(self):
class B3 (line 80) | class B3:
method spam (line 81) | def spam(self):
class C3 (line 85) | class C3(A3, B3):
FILE: cookbook/c08/p08_extend_property.py
class Person (line 9) | class Person:
method __init__ (line 10) | def __init__(self, name):
method name (line 15) | def name(self):
method name (line 20) | def name(self, value):
method name (line 27) | def name(self):
method __init__ (line 73) | def __init__(self, name):
class SubPerson (line 31) | class SubPerson(Person):
method name (line 33) | def name(self):
method name (line 38) | def name(self, value):
method name (line 43) | def name(self):
method name (line 80) | def name(self):
method name (line 85) | def name(self, value):
method name (line 90) | def name(self):
class String (line 54) | class String:
method __init__ (line 55) | def __init__(self, name):
method __get__ (line 58) | def __get__(self, instance, cls):
method __set__ (line 63) | def __set__(self, instance, value):
class Person (line 70) | class Person:
method __init__ (line 10) | def __init__(self, name):
method name (line 15) | def name(self):
method name (line 20) | def name(self, value):
method name (line 27) | def name(self):
method __init__ (line 73) | def __init__(self, name):
class SubPerson (line 78) | class SubPerson(Person):
method name (line 33) | def name(self):
method name (line 38) | def name(self, value):
method name (line 43) | def name(self):
method name (line 80) | def name(self):
method name (line 85) | def name(self, value):
method name (line 90) | def name(self):
FILE: cookbook/c08/p09_descriptor.py
class Integer (line 9) | class Integer:
method __init__ (line 10) | def __init__(self, name):
method __get__ (line 13) | def __get__(self, instance, cls):
method __set__ (line 19) | def __set__(self, instance, value):
method __delete__ (line 24) | def __delete__(self, instance):
class Point (line 28) | class Point:
method __init__ (line 32) | def __init__(self, x, y):
class Typed (line 43) | class Typed:
method __init__ (line 44) | def __init__(self, name, expected_type):
method __get__ (line 48) | def __get__(self, instance, cls):
method __set__ (line 54) | def __set__(self, instance, value):
method __delete__ (line 59) | def __delete__(self, instance):
function typeassert (line 64) | def typeassert(**kwargs):
class Stock (line 76) | class Stock:
method __init__ (line 77) | def __init__(self, name, shares, price):
FILE: cookbook/c08/p10_lazy_property.py
class lazyproperty (line 10) | class lazyproperty:
method __init__ (line 11) | def __init__(self, func):
method __get__ (line 14) | def __get__(self, instance, cls):
class Circle (line 23) | class Circle:
method __init__ (line 24) | def __init__(self, radius):
method area (line 28) | def area(self):
method perimeter (line 33) | def perimeter(self):
function lazyproperty2 (line 46) | def lazyproperty2(func):
FILE: cookbook/c08/p11_simplify_init.py
class Structure1 (line 10) | class Structure1:
method __init__ (line 14) | def __init__(self, *args):
class Stock (line 23) | class Stock(Structure1):
class Point (line 26) | class Point(Structure1):
class Circle (line 29) | class Circle(Structure1):
method area (line 32) | def area(self):
class Structure2 (line 40) | class Structure2:
method __init__ (line 43) | def __init__(self, *args, **kwargs):
class Stock (line 61) | class Stock(Structure2):
class Structure3 (line 70) | class Structure3:
method __init__ (line 74) | def __init__(self, *args, **kwargs):
class Stock (line 92) | class Stock(Structure3):
class Structure4 (line 99) | class Structure4:
method __init__ (line 102) | def __init__(self, *args):
FILE: cookbook/c08/p12_abstract_interface.py
class IStream (line 10) | class IStream(metaclass=ABCMeta):
method read (line 12) | def read(self, maxbytes=-1):
method write (line 16) | def write(self, data):
class SocketStream (line 20) | class SocketStream(IStream):
method read (line 21) | def read(self, maxbytes=-1):
method write (line 24) | def write(self, data):
class A (line 28) | class A(metaclass=ABCMeta):
method name (line 31) | def name(self):
method name (line 36) | def name(self, value):
method method1 (line 41) | def method1(cls):
method method2 (line 46) | def method2():
FILE: cookbook/c08/p13_type_system.py
class Descriptor (line 10) | class Descriptor:
method __init__ (line 11) | def __init__(self, name=None, **opts):
method __set__ (line 16) | def __set__(self, instance, value):
method __init__ (line 131) | def __init__(self, name=None, **opts):
method __set__ (line 136) | def __set__(self, instance, value):
class Typed (line 21) | class Typed(Descriptor):
method __set__ (line 24) | def __set__(self, instance, value):
class Unsigned (line 31) | class Unsigned(Descriptor):
method __set__ (line 32) | def __set__(self, instance, value):
class MaxSized (line 38) | class MaxSized(Descriptor):
method __init__ (line 39) | def __init__(self, name=None, **opts):
method __set__ (line 44) | def __set__(self, instance, value):
class Integer (line 51) | class Integer(Typed):
class UnsignedInteger (line 54) | class UnsignedInteger(Integer, Unsigned):
class Float (line 57) | class Float(Typed):
class UnsignedFloat (line 60) | class UnsignedFloat(Float, Unsigned):
class String (line 63) | class String(Typed):
class SizedString (line 66) | class SizedString(String, MaxSized):
class Stock (line 69) | class Stock:
method __init__ (line 75) | def __init__(self, name, shares, price):
method __init__ (line 100) | def __init__(self, name, shares, price):
function check_attributes (line 83) | def check_attributes(**kwargs):
class Stock (line 99) | class Stock:
method __init__ (line 75) | def __init__(self, name, shares, price):
method __init__ (line 100) | def __init__(self, name, shares, price):
class checkedmeta (line 108) | class checkedmeta(type):
method __new__ (line 109) | def __new__(cls, clsname, bases, methods):
class Stock2 (line 118) | class Stock2(metaclass=checkedmeta):
method __init__ (line 123) | def __init__(self, name, shares, price):
class Descriptor (line 130) | class Descriptor:
method __init__ (line 11) | def __init__(self, name=None, **opts):
method __set__ (line 16) | def __set__(self, instance, value):
method __init__ (line 131) | def __init__(self, name=None, **opts):
method __set__ (line 136) | def __set__(self, instance, value):
function Typed (line 141) | def Typed(expected_type, cls=None):
method __set__ (line 24) | def __set__(self, instance, value):
function Unsigned (line 156) | def Unsigned(cls):
method __set__ (line 32) | def __set__(self, instance, value):
function MaxSized (line 169) | def MaxSized(cls):
method __init__ (line 39) | def __init__(self, name=None, **opts):
method __set__ (line 44) | def __set__(self, instance, value):
class Integer (line 192) | class Integer(Descriptor):
class UnsignedInteger (line 197) | class UnsignedInteger(Integer):
class Float (line 202) | class Float(Descriptor):
class UnsignedFloat (line 207) | class UnsignedFloat(Float):
class String (line 212) | class String(Descriptor):
class SizedString (line 217) | class SizedString(String):
FILE: cookbook/c08/p14_custom_container.py
class SortedItems (line 12) | class SortedItems(collections.Sequence):
method __init__ (line 13) | def __init__(self, initial=None):
method __getitem__ (line 17) | def __getitem__(self, index):
method __len__ (line 20) | def __len__(self):
method add (line 24) | def add(self, item):
class Items (line 35) | class Items(collections.MutableSequence):
method __init__ (line 36) | def __init__(self, initial=None):
method __getitem__ (line 40) | def __getitem__(self, index):
method __setitem__ (line 44) | def __setitem__(self, index, value):
method __delitem__ (line 48) | def __delitem__(self, index):
method insert (line 52) | def insert(self, index, value):
method __len__ (line 56) | def __len__(self):
FILE: cookbook/c08/p15_delegate_attribute.py
class A (line 9) | class A:
method spam (line 10) | def spam(self, x):
method foo (line 13) | def foo(self):
method spam (line 133) | def spam(self, x):
method foo (line 136) | def foo(self):
method spam (line 150) | def spam(self, x):
method foo (line 153) | def foo(self):
class B1 (line 17) | class B1:
method __init__ (line 20) | def __init__(self):
method spam (line 23) | def spam(self, x):
method foo (line 27) | def foo(self):
method bar (line 31) | def bar(self):
class B2 (line 35) | class B2:
method __init__ (line 38) | def __init__(self):
method bar (line 41) | def bar(self):
method __getattr__ (line 45) | def __getattr__(self, name):
class Proxy (line 59) | class Proxy:
method __init__ (line 60) | def __init__(self, obj):
method __getattr__ (line 64) | def __getattr__(self, name):
method __setattr__ (line 69) | def __setattr__(self, name, value):
method __delattr__ (line 77) | def __delattr__(self, name):
class Spam (line 85) | class Spam:
method __init__ (line 86) | def __init__(self, x):
method bar (line 89) | def bar(self, y):
class ListLike (line 102) | class ListLike:
method __init__ (line 105) | def __init__(self):
method __getattr__ (line 108) | def __getattr__(self, name):
method __len__ (line 112) | def __len__(self):
method __getitem__ (line 115) | def __getitem__(self, index):
method __setitem__ (line 118) | def __setitem__(self, index, value):
method __delitem__ (line 121) | def __delitem__(self, index):
class A (line 132) | class A:
method spam (line 10) | def spam(self, x):
method foo (line 13) | def foo(self):
method spam (line 133) | def spam(self, x):
method foo (line 136) | def foo(self):
method spam (line 150) | def spam(self, x):
method foo (line 153) | def foo(self):
class B (line 140) | class B(A):
method spam (line 141) | def spam(self, x):
method bar (line 145) | def bar(self):
method __init__ (line 158) | def __init__(self):
method spam (line 161) | def spam(self, x):
method bar (line 165) | def bar(self):
method __getattr__ (line 168) | def __getattr__(self, name):
class A (line 149) | class A:
method spam (line 10) | def spam(self, x):
method foo (line 13) | def foo(self):
method spam (line 133) | def spam(self, x):
method foo (line 136) | def foo(self):
method spam (line 150) | def spam(self, x):
method foo (line 153) | def foo(self):
class B (line 157) | class B:
method spam (line 141) | def spam(self, x):
method bar (line 145) | def bar(self):
method __init__ (line 158) | def __init__(self):
method spam (line 161) | def spam(self, x):
method bar (line 165) | def bar(self):
method __getattr__ (line 168) | def __getattr__(self, name):
FILE: cookbook/c08/p16_more_constructor.py
class Date (line 11) | class Date:
method __init__ (line 14) | def __init__(self, year, month, day):
method today (line 21) | def today(cls):
FILE: cookbook/c08/p17_without_init.py
class Date (line 9) | class Date:
method __init__ (line 10) | def __init__(self, year, month, day):
method __init__ (line 26) | def __init__(self, year, month, day):
method today (line 32) | def today(cls):
class Date (line 25) | class Date:
method __init__ (line 10) | def __init__(self, year, month, day):
method __init__ (line 26) | def __init__(self, year, month, day):
method today (line 32) | def today(cls):
FILE: cookbook/c08/p18_mixin_classes.py
class LoggedMappingMixin (line 10) | class LoggedMappingMixin:
method __getitem__ (line 16) | def __getitem__(self, key):
method __setitem__ (line 20) | def __setitem__(self, key, value):
method __delitem__ (line 24) | def __delitem__(self, key):
class SetOnceMappingMixin (line 29) | class SetOnceMappingMixin:
method __setitem__ (line 35) | def __setitem__(self, key, value):
class StringKeysMappingMixin (line 41) | class StringKeysMappingMixin:
method __setitem__ (line 47) | def __setitem__(self, key, value):
class LoggedDict (line 53) | class LoggedDict(LoggedMappingMixin, dict):
class SetOnceDefaultDict (line 65) | class SetOnceDefaultDict(SetOnceMappingMixin, defaultdict):
function LoggedMapping (line 75) | def LoggedMapping(cls):
class LoggedDict (line 100) | class LoggedDict(dict):
FILE: cookbook/c08/p19_stateful_object.py
class Connection (line 9) | class Connection:
method __init__ (line 12) | def __init__(self):
method read (line 15) | def read(self):
method write (line 20) | def write(self, data):
method open (line 25) | def open(self):
method close (line 30) | def close(self):
class Connection1 (line 36) | class Connection1:
method __init__ (line 39) | def __init__(self):
method new_state (line 42) | def new_state(self, newstate):
method read (line 46) | def read(self):
method write (line 49) | def write(self, data):
method open (line 52) | def open(self):
method close (line 55) | def close(self):
class ConnectionState (line 60) | class ConnectionState:
method read (line 62) | def read(conn):
method write (line 66) | def write(conn, data):
method open (line 70) | def open(conn):
method close (line 74) | def close(conn):
class ClosedConnectionState (line 79) | class ClosedConnectionState(ConnectionState):
method read (line 81) | def read(conn):
method write (line 85) | def write(conn, data):
method open (line 89) | def open(conn):
method close (line 93) | def close(conn):
class OpenConnectionState (line 97) | class OpenConnectionState(ConnectionState):
method read (line 99) | def read(conn):
method write (line 103) | def write(conn, data):
method open (line 107) | def open(conn):
method close (line 111) | def close(conn):
class State (line 120) | class State:
method __init__ (line 121) | def __init__(self):
method new_state (line 124) | def new_state(self, state):
method action (line 127) | def action(self, x):
class State_A (line 131) | class State_A(State):
method action (line 132) | def action(self, x):
class State_B (line 138) | class State_B(State):
method action (line 139) | def action(self, x):
class State_C (line 145) | class State_C(State):
method action (line 146) | def action(self, x):
FILE: cookbook/c08/p20_invoke_bystr.py
class Point (line 11) | class Point:
method __init__ (line 12) | def __init__(self, x, y):
method __repr__ (line 16) | def __repr__(self):
method distance (line 20) | def distance(self, x, y):
FILE: cookbook/c08/p21_vistor_pattern.py
class Node (line 9) | class Node:
class UnaryOperator (line 13) | class UnaryOperator(Node):
method __init__ (line 14) | def __init__(self, operand):
class BinaryOperator (line 18) | class BinaryOperator(Node):
method __init__ (line 19) | def __init__(self, left, right):
class Add (line 24) | class Add(BinaryOperator):
class Sub (line 28) | class Sub(BinaryOperator):
class Mul (line 32) | class Mul(BinaryOperator):
class Div (line 36) | class Div(BinaryOperator):
class Negate (line 40) | class Negate(UnaryOperator):
class Number (line 44) | class Number(Node):
method __init__ (line 45) | def __init__(self, value):
class NodeVisitor (line 55) | class NodeVisitor:
method visit (line 56) | def visit(self, node):
method generic_visit (line 63) | def generic_visit(self, node):
class Evaluator (line 67) | class Evaluator(NodeVisitor):
method visit_Number (line 68) | def visit_Number(self, node):
method visit_Add (line 71) | def visit_Add(self, node):
method visit_Sub (line 74) | def visit_Sub(self, node):
method visit_Mul (line 77) | def visit_Mul(self, node):
method visit_Div (line 80) | def visit_Div(self, node):
method visit_Negate (line 83) | def visit_Negate(self, node):
class StackCode (line 91) | class StackCode(NodeVisitor):
method generate_code (line 92) | def generate_code(self, node):
method visit_Number (line 97) | def visit_Number(self, node):
method binop (line 100) | def binop(self, node, instruction):
method visit_Add (line 105) | def visit_Add(self, node):
method visit_Sub (line 108) | def visit_Sub(self, node):
method visit_Mul (line 111) | def visit_Mul(self, node):
method visit_Div (line 114) | def visit_Div(self, node):
method unaryop (line 117) | def unaryop(self, node, instruction):
method visit_Negate (line 121) | def visit_Negate(self, node):
class HTTPHandler (line 125) | class HTTPHandler:
method handle (line 126) | def handle(self, request):
method do_GET (line 129) | def do_GET(self, request):
method do_POST (line 131) | def do_POST(self, request):
method do_HEAD (line 133) | def do_HEAD(self, request):
FILE: cookbook/c08/p22_vistor_norecursiion.py
class Node (line 11) | class Node:
class NodeVisitor (line 15) | class NodeVisitor:
method visit (line 16) | def visit(self, node):
method _visit (line 34) | def _visit(self, node):
method generic_visit (line 41) | def generic_visit(self, node):
class UnaryOperator (line 45) | class UnaryOperator(Node):
method __init__ (line 46) | def __init__(self, operand):
class BinaryOperator (line 50) | class BinaryOperator(Node):
method __init__ (line 51) | def __init__(self, left, right):
class Add (line 56) | class Add(BinaryOperator):
class Sub (line 60) | class Sub(BinaryOperator):
class Mul (line 64) | class Mul(BinaryOperator):
class Div (line 68) | class Div(BinaryOperator):
class Negate (line 72) | class Negate(UnaryOperator):
class Number (line 76) | class Number(Node):
method __init__ (line 77) | def __init__(self, value):
class Evaluator (line 82) | class Evaluator(NodeVisitor):
method visit_Number (line 83) | def visit_Number(self, node):
method visit_Add (line 86) | def visit_Add(self, node):
method visit_Sub (line 89) | def visit_Sub(self, node):
method visit_Mul (line 92) | def visit_Mul(self, node):
method visit_Div (line 95) | def visit_Div(self, node):
method visit_Negate (line 98) | def visit_Negate(self, node):
FILE: cookbook/c08/p23_weakref.py
class Node (line 11) | class Node:
method __init__ (line 12) | def __init__(self, value):
method __repr__ (line 17) | def __repr__(self):
method parent (line 22) | def parent(self):
method parent (line 26) | def parent(self, node):
method add_child (line 29) | def add_child(self, child):
class Data (line 35) | class Data:
method __del__ (line 36) | def __del__(self):
class Node1 (line 41) | class Node1:
method __init__ (line 42) | def __init__(self):
method add_child (line 47) | def add_child(self, child):
FILE: cookbook/c08/p24_class_compare.py
class Room (line 11) | class Room:
method __init__ (line 12) | def __init__(self, name, length, width):
class House (line 20) | class House:
method __init__ (line 21) | def __init__(self, name, style):
method living_space_footage (line 27) | def living_space_footage(self):
method add_room (line 30) | def add_room(self, room):
method __str__ (line 33) | def __str__(self):
method __eq__ (line 38) | def __eq__(self, other):
method __lt__ (line 41) | def __lt__(self, other):
FILE: cookbook/c08/p25_cached_objects.py
class Spam (line 17) | class Spam:
method __init__ (line 18) | def __init__(self, name):
function get_spam (line 27) | def get_spam(name):
class Spam1 (line 37) | class Spam1:
method __new__ (line 40) | def __new__(cls, name):
method __init__ (line 49) | def __init__(self, name):
class CachedSpamManager (line 59) | class CachedSpamManager:
method __init__ (line 60) | def __init__(self):
method get_spam (line 63) | def get_spam(self, name):
method clear (line 71) | def clear(self):
class Spam2 (line 75) | class Spam2:
method __init__ (line 78) | def __init__(self, name):
function get_spam (line 81) | def get_spam(name):
class CachedSpamManager2 (line 86) | class CachedSpamManager2:
method __init__ (line 87) | def __init__(self):
method get_spam (line 90) | def get_spam(self, name):
method clear (line 98) | def clear(self):
class Spam3 (line 102) | class Spam3:
method __init__ (line 103) | def __init__(self, *args, **kwargs):
method _new (line 108) | def _new(cls, name):
FILE: cookbook/c09/p01_wrap_function.py
function timethis (line 12) | def timethis(func):
function countdown (line 26) | def countdown(n):
FILE: cookbook/c09/p02_preserve_metadata.py
function timethis (line 12) | def timethis(func):
function countdown (line 29) | def countdown(n: int):
FILE: cookbook/c09/p03_unwrap_decorator.py
function decorator1 (line 11) | def decorator1(func):
function decorator2 (line 19) | def decorator2(func):
function add (line 29) | def add(x, y):
FILE: cookbook/c09/p04_decorator_argument.py
function logged (line 12) | def logged(level, name=None, message=None):
function add (line 37) | def add(x, y):
function spam (line 42) | def spam():
FILE: cookbook/c09/p05_adjust_attribute.py
function attach_wrapper (line 14) | def attach_wrapper(obj, func=None):
function logged (line 21) | def logged(level, name=None, message=None):
function add (line 57) | def add(x, y):
function spam (line 62) | def spam():
function timethis (line 81) | def timethis(func):
function countdown (line 98) | def countdown(n):
function countdown1 (line 110) | def countdown1(n):
FILE: cookbook/c09/p06_optarg_decorator.py
function logged (line 11) | def logged(func=None, *, level=logging.DEBUG, name=None, message=None):
function add (line 29) | def add(x, y):
function spam (line 34) | def spam():
function aa (line 40) | def aa(kk=None, *, a=1,b=2,c=3):
FILE: cookbook/c09/p07_typecheck.py
function typeassert (line 12) | def typeassert(*ty_args, **ty_kwargs):
function add (line 39) | def add(x, y):
function bar (line 48) | def bar(x, items=None):
FILE: cookbook/c09/p08_inclass_decorator.py
class A (line 10) | class A:
method decorator1 (line 12) | def decorator1(self, func):
method decorator2 (line 21) | def decorator2(cls, func):
class Person (line 28) | class Person:
method first_name (line 34) | def first_name(self):
method first_name (line 38) | def first_name(self, value):
FILE: cookbook/c09/p09_class_decorator.py
class Profiled (line 11) | class Profiled:
method __init__ (line 12) | def __init__(self, func):
method __call__ (line 16) | def __call__(self, *args, **kwargs):
method __get__ (line 20) | def __get__(self, instance, cls):
function add (line 27) | def add(x, y):
class Spam (line 30) | class Spam:
method bar (line 32) | def bar(self, x):
function profiled (line 41) | def profiled(func):
function add (line 53) | def add(x, y):
FILE: cookbook/c09/p10_static_decorator.py
function timethis (line 12) | def timethis(func):
class Spam (line 23) | class Spam:
method instance_method (line 25) | def instance_method(self, n):
method class_method (line 32) | def class_method(cls, n):
method static_method (line 39) | def static_method(n):
class A (line 45) | class A(metaclass=ABCMeta):
method method (line 48) | def method(cls):
FILE: cookbook/c09/p11_add_argument.py
function optional_debug (line 12) | def optional_debug(func):
function spam (line 23) | def spam(a, b, c):
function a (line 31) | def a(x, debug=False):
function b (line 36) | def b(x, y, z, debug=False):
function c (line 41) | def c(x, y, debug=False):
function optional_debug (line 46) | def optional_debug(func):
function a (line 61) | def a(x):
function b (line 66) | def b(x, y, z):
function c (line 71) | def c(x, y):
function optional_debug1 (line 74) | def optional_debug1(func):
function add (line 93) | def add(x,y):
FILE: cookbook/c09/p12_patch_class.py
function log_getattribute (line 9) | def log_getattribute(cls):
class A (line 25) | class A:
method __init__ (line 26) | def __init__(self, x):
method spam (line 29) | def spam(self):
FILE: cookbook/c09/p13_instance_create.py
class NoInstances (line 9) | class NoInstances(type):
method __call__ (line 10) | def __call__(self, *args, **kwargs):
class Spam (line 15) | class Spam(metaclass=NoInstances):
method grok (line 17) | def grok(x):
class Singleton (line 21) | class Singleton(type):
method __init__ (line 22) | def __init__(self, *args, **kwargs):
method __call__ (line 26) | def __call__(self, *args, **kwargs):
class Spam1 (line 35) | class Spam1(metaclass=Singleton):
method __init__ (line 36) | def __init__(self):
class Cached (line 43) | class Cached(type):
method __init__ (line 44) | def __init__(self, *args, **kwargs):
method __call__ (line 48) | def __call__(self, *args):
class Spam2 (line 58) | class Spam2(metaclass=Cached):
method __init__ (line 59) | def __init__(self, name):
FILE: cookbook/c09/p14_attribute_order.py
class Typed (line 10) | class Typed:
method __init__ (line 13) | def __init__(self, name=None):
method __set__ (line 16) | def __set__(self, instance, value):
class Integer (line 22) | class Integer(Typed):
class Float (line 26) | class Float(Typed):
class String (line 30) | class String(Typed):
class OrderedMeta (line 35) | class OrderedMeta(type):
method __new__ (line 36) | def __new__(cls, clsname, bases, clsdict):
method __prepare__ (line 47) | def __prepare__(cls, clsname, bases):
class Structure (line 51) | class Structure(metaclass=OrderedMeta):
method as_csv (line 52) | def as_csv(self):
class Stock (line 57) | class Stock(Structure):
method __init__ (line 62) | def __init__(self, name, shares, price):
FILE: cookbook/c09/p15_meta_optional_arg.py
class IStream (line 10) | class IStream(metaclass=ABCMeta):
method read (line 12) | def read(self, maxsize=None):
method write (line 16) | def write(self, data):
class MyMeta (line 19) | class MyMeta(type):
method __prepare__ (line 22) | def __prepare__(cls, name, bases, *, debug=False, synchronize=False):
method __new__ (line 28) | def __new__(cls, name, bases, ns, *, debug=False, synchronize=False):
method __init__ (line 34) | def __init__(self, name, bases, ns, *, debug=False, synchronize=False):
FILE: cookbook/c09/p16_enforce_args.py
function make_sig (line 11) | def make_sig(*names):
class Structure (line 17) | class Structure:
method __init__ (line 20) | def __init__(self, *args, **kwargs):
method __init__ (line 53) | def __init__(self, *args, **kwargs):
class Stock (line 27) | class Stock(Structure):
class Point (line 31) | class Point(Structure):
function make_sig (line 38) | def make_sig(*names):
class StructureMeta (line 44) | class StructureMeta(type):
method __new__ (line 45) | def __new__(cls, clsname, bases, clsdict):
class Structure (line 50) | class Structure(metaclass=StructureMeta):
method __init__ (line 20) | def __init__(self, *args, **kwargs):
method __init__ (line 53) | def __init__(self, *args, **kwargs):
class Stock (line 60) | class Stock(Structure):
class Point (line 64) | class Point(Structure):
FILE: cookbook/c09/p17_code_convention.py
class MyMeta (line 9) | class MyMeta(type):
method __init__ (line 10) | def __init__(self, clsname, bases, clsdict):
class Root (line 17) | class Root(metaclass=MyMeta):
class A (line 21) | class A(Root):
method foo_bar (line 42) | def foo_bar(self): # Ok
method foo (line 75) | def foo(self, x, y):
method spam (line 78) | def spam(self, x, *, z):
class B (line 25) | class B(Root):
method fooBar (line 47) | def fooBar(self): # TypeError
method foo (line 83) | def foo(self, a, b):
method spam (line 86) | def spam(self,x,z):
class NoMixedCaseMeta (line 29) | class NoMixedCaseMeta(type):
method __new__ (line 30) | def __new__(cls, clsname, bases, clsdict):
class Root (line 37) | class Root(metaclass=NoMixedCaseMeta):
class A (line 41) | class A(Root):
method foo_bar (line 42) | def foo_bar(self): # Ok
method foo (line 75) | def foo(self, x, y):
method spam (line 78) | def spam(self, x, *, z):
class B (line 46) | class B(Root):
method fooBar (line 47) | def fooBar(self): # TypeError
method foo (line 83) | def foo(self, a, b):
method spam (line 86) | def spam(self,x,z):
class MatchSignaturesMeta (line 53) | class MatchSignaturesMeta(type):
method __init__ (line 55) | def __init__(self, clsname, bases, clsdict):
class Root (line 71) | class Root(metaclass=MatchSignaturesMeta):
class A (line 74) | class A(Root):
method foo_bar (line 42) | def foo_bar(self): # Ok
method foo (line 75) | def foo(self, x, y):
method spam (line 78) | def spam(self, x, *, z):
class B (line 82) | class B(A):
method fooBar (line 47) | def fooBar(self): # TypeError
method foo (line 83) | def foo(self, a, b):
method spam (line 86) | def spam(self,x,z):
FILE: cookbook/c09/p18_define_classes.py
function __init__ (line 12) | def __init__(self, name, shares, price):
function cost (line 18) | def cost(self):
function named_tuple (line 38) | def named_tuple(classname, fieldnames):
FILE: cookbook/c09/p19_define_init.py
class StructTupleMeta (line 11) | class StructTupleMeta(type):
method __init__ (line 12) | def __init__(cls, *args, **kwargs):
class StructTuple (line 18) | class StructTuple(tuple, metaclass=StructTupleMeta):
method __new__ (line 21) | def __new__(cls, *args):
class Stock (line 27) | class Stock(StructTuple):
class Point (line 31) | class Point(StructTuple):
FILE: cookbook/c09/p20_multiple_dispatch.py
class MultiMethod (line 13) | class MultiMethod:
method __init__ (line 18) | def __init__(self, name):
method register (line 22) | def register(self, meth):
method __call__ (line 47) | def __call__(self, *args):
method __get__ (line 58) | def __get__(self, instance, cls):
class MultiDict (line 68) | class MultiDict(dict):
method __setitem__ (line 73) | def __setitem__(self, key, value):
class MultipleMeta (line 88) | class MultipleMeta(type):
method __new__ (line 93) | def __new__(cls, clsname, bases, clsdict):
method __prepare__ (line 97) | def __prepare__(cls, clsname, bases):
class Spam (line 101) | class Spam(metaclass=MultipleMeta):
method bar (line 102) | def bar(self, x:int, y:int):
method bar (line 105) | def bar(self, s:str, n:int=0):
method bar (line 158) | def bar(self, *args):
method bar (line 163) | def bar(self, x, y):
method bar (line 167) | def bar(self, s, n=0):
class Date (line 112) | class Date(metaclass=MultipleMeta):
method __init__ (line 113) | def __init__(self, year: int, month:int, day:int):
method __init__ (line 118) | def __init__(self):
class multimethod (line 126) | class multimethod:
method __init__ (line 127) | def __init__(self, func):
method match (line 132) | def match(self, *types):
method __call__ (line 141) | def __call__(self, *args):
method __get__ (line 149) | def __get__(self, instance, cls):
class Spam (line 156) | class Spam:
method bar (line 102) | def bar(self, x:int, y:int):
method bar (line 105) | def bar(self, s:str, n:int=0):
method bar (line 158) | def bar(self, *args):
method bar (line 163) | def bar(self, x, y):
method bar (line 167) | def bar(self, s, n=0):
FILE: cookbook/c09/p21_avoid_repetitive.py
class Person (line 9) | class Person:
method __init__ (line 10) | def __init__(self, name, age):
method name (line 15) | def name(self):
method name (line 19) | def name(self, value):
method age (line 25) | def age(self):
method age (line 29) | def age(self, value):
method __init__ (line 56) | def __init__(self, name, age):
method __init__ (line 71) | def __init__(self, name, age):
function typed_property (line 35) | def typed_property(name, expected_type):
class Person (line 52) | class Person:
method __init__ (line 10) | def __init__(self, name, age):
method name (line 15) | def name(self):
method name (line 19) | def name(self, value):
method age (line 25) | def age(self):
method age (line 29) | def age(self, value):
method __init__ (line 56) | def __init__(self, name, age):
method __init__ (line 71) | def __init__(self, name, age):
class Person (line 67) | class Person:
method __init__ (line 10) | def __init__(self, name, age):
method name (line 15) | def name(self):
method name (line 19) | def name(self, value):
method age (line 25) | def age(self):
method age (line 29) | def age(self, value):
method __init__ (line 56) | def __init__(self, name, age):
method __init__ (line 71) | def __init__(self, name, age):
FILE: cookbook/c09/p22_context_manager.py
function timethis (line 12) | def timethis(label):
method __init__ (line 35) | def __init__(self, label):
method __enter__ (line 38) | def __enter__(self):
method __exit__ (line 41) | def __exit__(self, exc_ty, exc_val, exc_tb):
function list_transaction (line 27) | def list_transaction(orig_list):
class timethis (line 34) | class timethis:
method __init__ (line 35) | def __init__(self, label):
method __enter__ (line 38) | def __enter__(self):
method __exit__ (line 41) | def __exit__(self, exc_ty, exc_val, exc_tb):
FILE: cookbook/c09/p23_local_side.py
function test3 (line 8) | def test3():
function test4 (line 18) | def test4():
FILE: cookbook/c09/p24_analyze_source.py
class CodeAnalyzer (line 11) | class CodeAnalyzer(ast.NodeVisitor):
method __init__ (line 12) | def __init__(self):
method visit_Name (line 17) | def visit_Name(self, node):
class NameLower (line 51) | class NameLower(ast.NodeVisitor):
method __init__ (line 52) | def __init__(self, lowered_names):
method visit_FunctionDef (line 55) | def visit_FunctionDef(self, node):
function lower_names (line 70) | def lower_names(*namelist):
FILE: cookbook/c09/p25_disassemble_bytecode.py
function generate_opcodes (line 11) | def generate_opcodes(codebytes):
FILE: cookbook/c10/p02_control_import.py
function spam (line 9) | def spam():
function grok (line 13) | def grok():
FILE: cookbook/c10/p12_import_patch.py
class PostImportFinder (line 15) | class PostImportFinder:
method __init__ (line 16) | def __init__(self):
method find_module (line 19) | def find_module(self, fullname, path=None):
class PostImportLoader (line 26) | class PostImportLoader:
method __init__ (line 27) | def __init__(self, finder):
method load_module (line 30) | def load_module(self, fullname):
function when_imported (line 39) | def when_imported(fullname):
function logged (line 54) | def logged(func):
function add_logging (line 65) | def add_logging(mod):
FILE: cookbook/c12/p01_start_stop_thread.py
function countdown (line 4) | def countdown(n):
class CountdownTask (line 26) | class CountdownTask:
method __init__ (line 27) | def __init__(self):
method terminate (line 30) | def terminate(self):
method run (line 33) | def run(self, n):
class IOTask (line 48) | class IOTask:
method terminate (line 49) | def terminate(self):
class CountdownThread (line 65) | class CountdownThread(Thread):
method __init__ (line 66) | def __init__(self, n):
method run (line 70) | def run(self):
FILE: exts/chinese_search.py
function setup (line 3) | def setup(app):
FILE: exts/smallseg.py
class SEG (line 12) | class SEG(object):
method __init__ (line 13) | def __init__(self):
method set (line 25) | def set(self,keywords):
method _binary_seg (line 46) | def _binary_seg(self,s):
method _pro_unreg (line 56) | def _pro_unreg(self,piece):
method cut (line 72) | def cut(self,text):
FILE: exts/zh.py
class SearchChinese (line 5) | class SearchChinese(SearchLanguage):
method init (line 8) | def init(self, options):
method split (line 12) | def split(self, input):
method word_filter (line 15) | def word_filter(self, stemmed_word):
FILE: notebook/fetch_cookbook.py
class Chapter (line 55) | class Chapter:
method __init__ (line 56) | def __init__(self, chapter_address):
method fetch (line 61) | def fetch(self, url):
method fetch_list (line 72) | def fetch_list(self):
method fetch_sections (line 82) | def fetch_sections(self, sep=False):
method fetch_content (line 102) | def fetch_content(self, url):
function fetch_all (line 162) | def fetch_all(sep=False):
Condensed preview — 827 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (7,524K chars).
[
{
"path": ".gitignore",
"chars": 19,
"preview": "build/\n.idea/\n*.pyc"
},
{
"path": ".travis.yml",
"chars": 567,
"preview": "language: python\ncache: pip\npython:\n - 3.6\ninstall:\n - pip install flake8\nbefore_script:\n # stop the build if t"
},
{
"path": "Makefile",
"chars": 6811,
"preview": "# Makefile for Sphinx documentation\n#\n\n# You can set these variables from the command line.\nSPHINXOPTS =\nSPHINXBUILD "
},
{
"path": "README.md",
"chars": 4846,
"preview": "\n[](https://github.com/yidao620c/py"
},
{
"path": "README_en.md",
"chars": 6477,
"preview": "\n[](https://github.com/yidao620c/py"
},
{
"path": "cookbook/__init__.py",
"chars": 79,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: sample\nDesc : \n\"\"\"\n\n"
},
{
"path": "cookbook/c01/__init__.py",
"chars": 79,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: sample\nDesc : \n\"\"\"\n\n"
},
{
"path": "cookbook/c01/p03_nitem.py",
"chars": 664,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: collections.deque演示\nDesc : deque有一个maxlen参数,当append的时候,如果超过,那"
},
{
"path": "cookbook/c01/p04_nlargest.py",
"chars": 875,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 返回集合中最大或最小的N个元素\nDesc : \n\"\"\"\nimport heapq\n\n\ndef main():\n po"
},
{
"path": "cookbook/c01/p05_priority_queue.py",
"chars": 383,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 优先级队列\nDesc : \n\"\"\"\nimport heapq\n\n\nclass PriorityQueue:\n def"
},
{
"path": "cookbook/c01/p06_multidict.py",
"chars": 447,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 多值映射\nDesc : \n\"\"\"\n\nfrom collections import defaultdict\n\n\ndef m"
},
{
"path": "cookbook/c01/p07_ordered_dict.py",
"chars": 272,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 排序字典\nDesc : \n\"\"\"\n\nfrom collections import OrderedDict\n\n\nd = O"
},
{
"path": "cookbook/c01/p08_calculate_dict.py",
"chars": 1231,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 字典的数据运算\nDesc : \n\"\"\"\n\n\ndef calc_dict():\n prices = {\n "
},
{
"path": "cookbook/c01/p09_dict_common.py",
"chars": 604,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 字典的集合操作\nDesc : \n\"\"\"\n\n\ndef dict_commonality():\n a = {\n "
},
{
"path": "cookbook/c01/p10_remove_duplicate.py",
"chars": 790,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 消除序列重复值并保持顺序\nDesc : \n\"\"\"\n\n\ndef dedupe(items):\n \"\"\"元素都是hash"
},
{
"path": "cookbook/c01/p11_naming_slice.py",
"chars": 587,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 命名切片\nDesc : \n\"\"\"\n\n\ndef name_slice():\n record = '.........."
},
{
"path": "cookbook/c01/p12_mostfreq_items.py",
"chars": 638,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 查找出现次数最多的元素\nDesc : \n\"\"\"\n\n\ndef most_freqency():\n words = [\n"
},
{
"path": "cookbook/c01/p13_sort_dictlist.py",
"chars": 697,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 排序dict列表\nDesc : \n\"\"\"\n\n\ndef sort_dictlist():\n rows = [\n "
},
{
"path": "cookbook/c01/p14_sort_nocompare.py",
"chars": 677,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 排序不支持原生比较操作的对象\nDesc : \n\"\"\"\n\n\nclass User:\n def __init__(sel"
},
{
"path": "cookbook/c01/p15_group.py",
"chars": 1104,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 分组迭代\nDesc : \n\"\"\"\nfrom operator import itemgetter\nfrom itertoo"
},
{
"path": "cookbook/c01/p16_filter.py",
"chars": 1125,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 序列元素过滤\nDesc :\n\"\"\"\nfrom itertools import compress\n\n\ndef cb_fil"
},
{
"path": "cookbook/c01/p17_subdict.py",
"chars": 552,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: dict子集\nDesc : \n\"\"\"\n\n\ndef sub_dict():\n prices = {\n '"
},
{
"path": "cookbook/c01/p18_nameseq.py",
"chars": 1421,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 通过名称访问序列\nDesc : \n\"\"\"\nfrom collections import namedtuple\n\n\ndef"
},
{
"path": "cookbook/c01/p19_trans_reduce.py",
"chars": 977,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 转换并聚集函数\nDesc : \n\"\"\"\nimport os\n\n\ndef trans_reduce():\n nums "
},
{
"path": "cookbook/c01/p20_combine_map.py",
"chars": 936,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 合并多个字典或映射\nDesc : \n\"\"\"\n\nfrom collections import ChainMap\n\n\ndef"
},
{
"path": "cookbook/c02/__init__.py",
"chars": 79,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: sample\nDesc : \n\"\"\"\n\n"
},
{
"path": "cookbook/c02/p01_splitstr.py",
"chars": 446,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 正则式分割字符串\nDesc : \n\"\"\"\nimport re\n\n\ndef split_str():\n line = "
},
{
"path": "cookbook/c02/p02_str_start.py",
"chars": 1140,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 检查字符串开始或结尾\nDesc : \n\"\"\"\nimport re\nimport os\nfrom urllib.reques"
},
{
"path": "cookbook/c02/p03_unix_match.py",
"chars": 840,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: Unix Shell通配符匹配\nDesc : \n\"\"\"\nfrom fnmatch import fnmatch, fnma"
},
{
"path": "cookbook/c02/p04_match_search.py",
"chars": 1599,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 字符串匹配和搜索\nDesc : \n\"\"\"\nimport re\n\n\ndef match_search():\n # 字"
},
{
"path": "cookbook/c02/p05_search_replace.py",
"chars": 907,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 字符串搜索和替换\nDesc : \n\"\"\"\nimport re\nfrom calendar import month_abb"
},
{
"path": "cookbook/c02/p06_case_insensitive.py",
"chars": 778,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 忽略大小写\nDesc : \n\"\"\"\nimport re\n\n\ndef matchcase(word):\n de"
},
{
"path": "cookbook/c02/p07_shortest_match.py",
"chars": 452,
"preview": "\n#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 最短匹配,非贪婪模式匹配\nDesc : \n\"\"\"\nimport re\n\n\ndef short_match():\n "
},
{
"path": "cookbook/c02/p08_multiline_match.py",
"chars": 582,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 多行匹配\nDesc : \n\"\"\"\nimport re\n\n\ndef multiline_match():\n comme"
},
{
"path": "cookbook/c02/p09_normal_unicode.py",
"chars": 1020,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: unicode字符串标准化表示\nDesc : \n\"\"\"\nimport unicodedata\n\n\ndef nor_unic"
},
{
"path": "cookbook/c02/p10_re_unicode.py",
"chars": 570,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 在正则式中使用Unicode\nDesc : \n\"\"\"\nimport re\n\n\ndef re_unicode():\n "
},
{
"path": "cookbook/c02/p11_strip.py",
"chars": 616,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 去除字符串中多余字符\nDesc : \n\"\"\"\nimport re\n\n\ndef strip_str():\n s = '"
},
{
"path": "cookbook/c02/p12_translate.py",
"chars": 1180,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: str的translate方法清理文本\nDesc : \n\"\"\"\nimport unicodedata\nimport sys"
},
{
"path": "cookbook/c02/p13_align_str.py",
"chars": 639,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 对齐字符串\nDesc : \n\"\"\"\n\n\ndef align_str():\n text = 'Hello World'"
},
{
"path": "cookbook/c02/p14_join_str.py",
"chars": 1102,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 字符串合并\nDesc : \n\"\"\"\n\n\ndef combine(source, maxsize):\n parts ="
},
{
"path": "cookbook/c02/p15_var_string.py",
"chars": 796,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 字符串中的变量\nDesc : \n\"\"\"\nimport sys\n\nclass Info:\n def __init__("
},
{
"path": "cookbook/c02/p16_textwrap.py",
"chars": 650,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 格式化字符串为指定宽度\nDesc : \n\"\"\"\nimport textwrap\nimport os\n\n\ndef refor"
},
{
"path": "cookbook/c02/p17_html_xml.py",
"chars": 406,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 处理html和xml文本\nDesc : \n\"\"\"\nimport html\n\n\ndef html_xml():\n s "
},
{
"path": "cookbook/c02/p18_tokenize.py",
"chars": 1920,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 字符串令牌化\nDesc : \n\"\"\"\nimport re\nfrom collections import namedtup"
},
{
"path": "cookbook/c02/p19_descent_parser.py",
"chars": 4008,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 下降解析器\nDesc : \n\"\"\"\nimport re\nimport collections\n\n# Token speci"
},
{
"path": "cookbook/c02/p20_byte_str.py",
"chars": 728,
"preview": "\n#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 字节字符串操作\nDesc : \n\"\"\"\nimport re\n\n\ndef byte_str():\n data = b"
},
{
"path": "cookbook/c03/__init__.py",
"chars": 79,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: sample\nDesc : \n\"\"\"\n\n"
},
{
"path": "cookbook/c03/p01_round.py",
"chars": 614,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 四舍五入运算\nDesc : \n\"\"\"\n\n\ndef round_num():\n print(round(1.23, 1"
},
{
"path": "cookbook/c03/p02_accurate_decimal.py",
"chars": 632,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 精确的浮点数运算\nDesc : \n\"\"\"\nfrom decimal import Decimal\nfrom decimal"
},
{
"path": "cookbook/c03/p03_format_number.py",
"chars": 803,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 格式化输出数字\nDesc : \n\"\"\"\n\n\ndef format_number():\n x = 1234.56789"
},
{
"path": "cookbook/c03/p04_bin_octal.py",
"chars": 381,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 不同进制的数字表示输出\nDesc : \n\"\"\"\n\n\ndef bin_octal():\n x = 1234\n p"
},
{
"path": "cookbook/c03/p05_int_bytes.py",
"chars": 619,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 大整数与字节的相互转换\nDesc : \n\"\"\"\n\n\ndef int_bytes():\n data = b'\\x00\\"
},
{
"path": "cookbook/c03/p06_complex.py",
"chars": 315,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: sample\nDesc : \n\"\"\"\nimport cmath\n\n\ndef complex_math():\n a ="
},
{
"path": "cookbook/c03/p07_inf_nan.py",
"chars": 390,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 无穷大与NaN\nDesc : \n\"\"\"\n\n\ndef inf_nan():\n a = float('inf')\n "
},
{
"path": "cookbook/c03/p08_fraction.py",
"chars": 379,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 分数运算\nDesc : \n\"\"\"\nfrom fractions import Fraction\n\n\ndef frac():"
},
{
"path": "cookbook/c03/p09_array_numpy.py",
"chars": 1053,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 利用numpy执行数组运算\nDesc : \n\"\"\"\nimport numpy as np\n\n\ndef array_nump"
},
{
"path": "cookbook/c03/p10_matrix_linear.py",
"chars": 658,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 矩阵和线性代数\nDesc : \n\"\"\"\nimport numpy as np\nimport numpy.linalg\n\n\n"
},
{
"path": "cookbook/c03/p11_random_num.py",
"chars": 911,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 随机数\nDesc : \n\"\"\"\nimport random\n\n\ndef random_num():\n values "
},
{
"path": "cookbook/c03/p12_datatime.py",
"chars": 1010,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 日期时间转换\nDesc : \n\"\"\"\nfrom datetime import timedelta\nfrom dateti"
},
{
"path": "cookbook/c03/p13_last_friday.py",
"chars": 1302,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 最后的周五\nDesc : \n\"\"\"\nfrom datetime import datetime, timedelta\nfr"
},
{
"path": "cookbook/c03/p14_month_range.py",
"chars": 906,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 计算当前月份的日期范围\nDesc : \n\"\"\"\nfrom datetime import datetime, date, "
},
{
"path": "cookbook/c03/p15_str_datetime.py",
"chars": 531,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 字符串转换为datetime\nDesc : \n\"\"\"\nfrom datetime import datetime\n\n\nde"
},
{
"path": "cookbook/c03/p16_timezone.py",
"chars": 1044,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 日期时区和本地化\nDesc : \n\"\"\"\nfrom datetime import datetime, timedelta"
},
{
"path": "cookbook/c04/__init__.py",
"chars": 79,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: sample\nDesc : \n\"\"\"\n\n"
},
{
"path": "cookbook/c04/p01_manual_iterator.py",
"chars": 518,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 手动遍历迭代器\nDesc : \n\"\"\"\n\n\ndef manual_iter():\n with open('/etc/"
},
{
"path": "cookbook/c04/p02_delegate_iter.py",
"chars": 601,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 代理迭代\nDesc : \n\"\"\"\n\n\nclass Node:\n def __init__(self, value):"
},
{
"path": "cookbook/c04/p03_generator_pattern.py",
"chars": 635,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 使用生成器创建新的迭代模式\nDesc : \n\"\"\"\n\n\ndef frange(start, stop, increment"
},
{
"path": "cookbook/c04/p04_iterator_protocol.py",
"chars": 2179,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 自定义迭代器协议\nDesc : \n\"\"\"\n\n\nclass Node:\n def __init__(self, val"
},
{
"path": "cookbook/c04/p05_reverse_iterate.py",
"chars": 847,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 方向迭代\nDesc : \n\"\"\"\n\n\ndef reverse_iterate():\n a = [1, 2, 3, 4"
},
{
"path": "cookbook/c04/p06_generator_extrastate.py",
"chars": 767,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 带外部状态的生成器\nDesc : \n\"\"\"\nfrom collections import deque\n\n\nclass l"
},
{
"path": "cookbook/c04/p07_iterator_slice.py",
"chars": 305,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 迭代器和生成器切片\nDesc : \n\"\"\"\nimport itertools\n\n\ndef count(n):\n wh"
},
{
"path": "cookbook/c04/p08_skip_iterable.py",
"chars": 472,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 跳过可迭代对象开始部分\nDesc : \n\"\"\"\nfrom itertools import dropwhile\nfrom "
},
{
"path": "cookbook/c04/p09_iter_permutation.py",
"chars": 597,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 排列组合迭代\nDesc : \n\"\"\"\nfrom itertools import permutations\nfrom it"
},
{
"path": "cookbook/c04/p10_iterate_index.py",
"chars": 1199,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 迭代并跟踪索引\nDesc : \n\"\"\"\nfrom collections import defaultdict\n\n\ndef"
},
{
"path": "cookbook/c04/p11_iterate_simultaneous.py",
"chars": 703,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 同时迭代多个序列\nDesc : \n\"\"\"\nfrom itertools import zip_longest\n\n\ndef "
},
{
"path": "cookbook/c04/p12_iterate_separate.py",
"chars": 268,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 在不同容器中迭代\nDesc : \n\"\"\"\nfrom itertools import chain\n\n\ndef iter_s"
},
{
"path": "cookbook/c04/p13_process_pipline.py",
"chars": 1829,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: sample\nDesc : \n\"\"\"\n\nimport os\nimport fnmatch\nimport gzip\nimpo"
},
{
"path": "cookbook/c04/p14_flatten_sequence.py",
"chars": 601,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: sample\nDesc : \n\"\"\"\nfrom collections import Iterable\n\n\ndef fla"
},
{
"path": "cookbook/c04/p15_merge_sorted.py",
"chars": 494,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: sample\nDesc : \n\"\"\"\nimport heapq\n\n\ndef merge_sorted():\n a ="
},
{
"path": "cookbook/c04/p16_iterate_while.py",
"chars": 598,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 使用迭代器重写while无限循环\nDesc : \n\"\"\"\nimport sys\n\n\ndef process_data():"
},
{
"path": "cookbook/c05/__init__.py",
"chars": 79,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: sample\nDesc : \n\"\"\"\n\n"
},
{
"path": "cookbook/c05/p01_rw_text.py",
"chars": 419,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 读写文本文件\nDesc : \n\"\"\"\n\ndef rw_text():\n # Iterate over the lin"
},
{
"path": "cookbook/c05/p02_print_tofile.py",
"chars": 232,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 输出重定向到文件\nDesc : \n\"\"\"\n\n\ndef print_tofile():\n with open('d:/"
},
{
"path": "cookbook/c05/p03_print_sepend.py",
"chars": 423,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: print分隔符和结尾符\nDesc : \n\"\"\"\n\ndef print_sepend():\n print('ACME"
},
{
"path": "cookbook/c05/p04_rw_binary.py",
"chars": 517,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 读写二进制文件\nDesc : \n\"\"\"\n\n\ndef rw_binary():\n # Read the entire "
},
{
"path": "cookbook/c05/p05_write_notexist.py",
"chars": 301,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 文件不存在时才写入\nDesc : \n\"\"\"\n\n\ndef write_noexist():\n with open('D"
},
{
"path": "cookbook/c05/p06_string_io.py",
"chars": 441,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 字符串的I/O操作\nDesc : \n\"\"\"\nimport io\n\n\ndef string_io():\n s = io"
},
{
"path": "cookbook/c05/p07_gzip_bz2.py",
"chars": 637,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 读写压缩文件\nDesc : \n\"\"\"\nimport gzip\nimport bz2\n\n\ndef gzip_bz2():\n "
},
{
"path": "cookbook/c05/p08_iterate_fixedsize.py",
"chars": 352,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 固定长度迭代文件\nDesc : \n\"\"\"\nfrom functools import partial\n\n\ndef iter"
},
{
"path": "cookbook/c05/p09_read_tobuffer.py",
"chars": 532,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 读取二进制数据到可变缓冲区中\nDesc : \n\"\"\"\nimport os.path\n\n\ndef read_into_buf"
},
{
"path": "cookbook/c05/p10_memery_mapping.py",
"chars": 354,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 文件的内存映射\nDesc : \n\"\"\"\nimport os\nimport mmap\n\n\ndef memory_map(fi"
},
{
"path": "cookbook/c05/p11_pathnames.py",
"chars": 425,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 操作路径名\nDesc : \n\"\"\"\nimport os\n\n\ndef path_names():\n path = '/"
},
{
"path": "cookbook/c05/p12_file_existence.py",
"chars": 589,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 测试文件或目录是否存在\nDesc : \n\"\"\"\nimport os\nimport time\n\n\ndef file_exis"
},
{
"path": "cookbook/c05/p13_dir_listfile.py",
"chars": 1218,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 目录文件列表\nDesc : \n\"\"\"\nimport os\nimport os.path\nimport glob\nfrom "
},
{
"path": "cookbook/c05/p14_bypass_encode.py",
"chars": 205,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 忽略文件名编码\nDesc : \n\"\"\"\nimport sys\n\n\ndef bypass_encoding():\n p"
},
{
"path": "cookbook/c05/p15_print_badfile.py",
"chars": 603,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 打印不合法文件名\nDesc : \n\"\"\"\nimport os\nimport sys\n\n\ndef bad_filename("
},
{
"path": "cookbook/c05/p16_change_opencode.py",
"chars": 559,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 增加/修改已打开文件的编码\nDesc : \n\"\"\"\nimport urllib.request\nimport io\nimp"
},
{
"path": "cookbook/c05/p17_bytes_tofile.py",
"chars": 205,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 在文本模式文件中写入字节\nDesc : \n\"\"\"\nimport sys\n\n\ndef bytes_tofile():\n "
},
{
"path": "cookbook/c05/p18_file_descriptor.py",
"chars": 1258,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 文件描述符到文件的转换\nDesc : \n\"\"\"\nimport os\nimport sys\nfrom socket impo"
},
{
"path": "cookbook/c05/p19_temp_file.py",
"chars": 774,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 临时文件和目录\nDesc : \n\"\"\"\nfrom tempfile import TemporaryFile\nfrom t"
},
{
"path": "cookbook/c05/p20_serial_ports.py",
"chars": 382,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 串行端口数据交换\nDesc : \n\"\"\"\nimport serial\n\n\ndef serial_posts():\n "
},
{
"path": "cookbook/c05/p21_serialize_object.py",
"chars": 696,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 序列化一个对象\nDesc : \n\"\"\"\nimport pickle\n\n\ndef serailize_object():\n "
},
{
"path": "cookbook/c06/__init__.py",
"chars": 79,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: sample\nDesc : \n\"\"\"\n\n"
},
{
"path": "cookbook/c06/data.json",
"chars": 48,
"preview": "{\"name\": \"ACME\", \"shares\": 100, \"price\": 542.23}"
},
{
"path": "cookbook/c06/p01_rw_csv.py",
"chars": 977,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 读写CSV数据\nDesc : \n\"\"\"\nimport csv\nfrom collections import namedt"
},
{
"path": "cookbook/c06/p02_rw_json.py",
"chars": 1684,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: JSON读写\nDesc :\n\"\"\"\nimport json\nfrom collections import Ordered"
},
{
"path": "cookbook/c06/p03_simple_xml.py",
"chars": 618,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 解析简单的XML\nDesc : \n\"\"\"\nfrom urllib.request import urlopen\nfrom "
},
{
"path": "cookbook/c06/p04_huge_xml.py",
"chars": 1370,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 增量式的处理大型XML文档\nDesc : \n\"\"\"\nfrom xml.etree.ElementTree import i"
},
{
"path": "cookbook/c06/p05_dict_toxml.py",
"chars": 583,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 字典转换成XML格式\nDesc : \n\"\"\"\nfrom xml.etree.ElementTree import Elem"
},
{
"path": "cookbook/c06/p06_rw_xml.py",
"chars": 589,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 读取修改某个XML文档\nDesc : \n\"\"\"\nfrom xml.etree.ElementTree import par"
},
{
"path": "cookbook/c06/p07_namespace_xml.py",
"chars": 609,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 处理含命名空间的XML文档\nDesc : \n\"\"\"\n\n\nclass XMLNamespaces:\n def __in"
},
{
"path": "cookbook/c06/p08_database.py",
"chars": 760,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 关系型数据库处理\nDesc : \n\"\"\"\nimport sqlite3\nimport datetime.time\n\n\nde"
},
{
"path": "cookbook/c06/p09_codec_hex.py",
"chars": 487,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 编码/解码十六进制原始字符串\nDesc : \n\"\"\"\nimport binascii\nimport base64\n\n\nde"
},
{
"path": "cookbook/c06/p10_codec_base64.py",
"chars": 317,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 编码/解码Base64\nDesc : \n\"\"\"\nimport base64\n\n\ndef codec_base64():\n "
},
{
"path": "cookbook/c06/p11_rw_barray.py",
"chars": 1670,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 读写二进制数组结构的数据\nDesc : \n\"\"\"\nfrom struct import Struct\nfrom colle"
},
{
"path": "cookbook/c06/p12_var_binary.py",
"chars": 1546,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 读写变长的二进制格式文件\nDesc : \n\"\"\"\nimport struct\nimport itertools\n\npoly"
},
{
"path": "cookbook/c06/pred.xml",
"chars": 419,
"preview": "<?xml version=\"1.0\"?>\n<stop>\n <id>14791</id>\n <nm>Clark & Balmoral</nm>\n <sri>\n <rt>22</rt>\n "
},
{
"path": "cookbook/c06/stocks.csv",
"chars": 164,
"preview": "Symbol,Price,Date,Time,Change,Volume\r\r\nAA,39.48,6/11/2007,9:36am,-0.18,181800\r\r\nAIG,71.38,6/11/2007,9:36am,-0.15,195500\r"
},
{
"path": "cookbook/c07/__init__.py",
"chars": 79,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: sample\nDesc : \n\"\"\"\n\n"
},
{
"path": "cookbook/c07/p02_keyarg_only.py",
"chars": 424,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 只允许关键字形式的参数\nDesc : \n\"\"\"\n\n\ndef recv(maxsize, *, block):\n 'R"
},
{
"path": "cookbook/c07/p03_func_annotate.py",
"chars": 167,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 函数注解元信息\nDesc : \n\"\"\"\n\ndef add(x:int, y:int) -> int:\n return"
},
{
"path": "cookbook/c07/p05_default_argument.py",
"chars": 275,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 函数默认参数\nDesc : \n\"\"\"\n\ndef spam(a, b=42):\n print(a, b)\n\nspam("
},
{
"path": "cookbook/c07/p06_anony_func.py",
"chars": 127,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 匿名函数lambda表达式\nDesc : \n\"\"\"\n\nadd = lambda x, y: x + y\nprint(add"
},
{
"path": "cookbook/c07/p08_partial.py",
"chars": 1358,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 使用partial函数来减少参数个数\nDesc : \n\"\"\"\nimport logging\nfrom multiproce"
},
{
"path": "cookbook/c07/p09_class_to_func.py",
"chars": 874,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 单方法类转换为函数\nDesc : \n\"\"\"\n\nfrom urllib.request import urlopen\n\n\nc"
},
{
"path": "cookbook/c07/p10_callback.py",
"chars": 1246,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 带状态值的回调函数\nDesc : \n\"\"\"\n\n\ndef apply_async(func, args, *, callba"
},
{
"path": "cookbook/c07/p11_inline_callback.py",
"chars": 1413,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 内联回调函数\nDesc : \n\"\"\"\nfrom queue import Queue\nfrom functools imp"
},
{
"path": "cookbook/c07/p12_closure_access.py",
"chars": 1142,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 闭包访问函数内部变量\nDesc : \n\"\"\"\n\n\ndef sample():\n n = 0\n # Closur"
},
{
"path": "cookbook/c08/__init__.py",
"chars": 79,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: sample\nDesc : \n\"\"\"\n\n"
},
{
"path": "cookbook/c08/p01_str_represent.py",
"chars": 340,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 实例的字符串显示\nDesc : \n\"\"\"\n\n\nclass Pair:\n def __init__(self, x, "
},
{
"path": "cookbook/c08/p02_custom_format.py",
"chars": 625,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 对象自定义格式化\nDesc : \n\"\"\"\n_formats = {\n 'ymd': '{d.year}-{d.mon"
},
{
"path": "cookbook/c08/p03_context_protocol.py",
"chars": 1695,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 让对象支持上下文管理器\nDesc : \n\"\"\"\n\nfrom socket import socket, AF_INET, "
},
{
"path": "cookbook/c08/p04_slots.py",
"chars": 260,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 使用slots来减少内存占用\nDesc : \n\"\"\"\n\n\nclass Date:\n __slots__ = ['ye"
},
{
"path": "cookbook/c08/p05_encapsulate_name.py",
"chars": 746,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 隐藏私有属性\nDesc : \n\"\"\"\n\n\nclass A:\n def __init__(self):\n "
},
{
"path": "cookbook/c08/p06_managed_attribute.py",
"chars": 1832,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 可管理的属性\nDesc : \n\"\"\"\nimport math\n\n\nclass Person:\n def __init"
},
{
"path": "cookbook/c08/p07_super_method.py",
"chars": 1430,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: sample\nDesc : \n\"\"\"\n\n\nclass A:\n def spam(self):\n pri"
},
{
"path": "cookbook/c08/p08_extend_property.py",
"chars": 1945,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 扩展property的功能\nDesc : \n\"\"\"\n\n\nclass Person:\n def __init__(se"
},
{
"path": "cookbook/c08/p09_descriptor.py",
"chars": 1907,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 通过描述器定义新的实例属性\nDesc : \n\"\"\"\n\n# Descriptor attribute for an inte"
},
{
"path": "cookbook/c08/p10_lazy_property.py",
"chars": 1098,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 延迟属性\nDesc : \n\"\"\"\nimport math\n\n\nclass lazyproperty:\n def __"
},
{
"path": "cookbook/c08/p11_simplify_init.py",
"chars": 2964,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 简化数据结构的初始化\nDesc : \n\"\"\"\nimport math\n\n\nclass Structure1:\n # "
},
{
"path": "cookbook/c08/p12_abstract_interface.py",
"chars": 721,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 定义接口或抽象类\nDesc : \n\"\"\"\nfrom abc import ABCMeta, abstractmethod\n"
},
{
"path": "cookbook/c08/p13_type_system.py",
"chars": 5144,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 类型检查系统\nDesc : \n\"\"\"\n\n\n# Base class. Uses a descriptor to set a"
},
{
"path": "cookbook/c08/p14_custom_container.py",
"chars": 1382,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 自定义容器\nDesc : \n\"\"\"\n\nimport collections\nimport bisect\n\n\nclass S"
},
{
"path": "cookbook/c08/p15_delegate_attribute.py",
"chars": 3276,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 属性访问代理\nDesc : \n\"\"\"\n\n\nclass A:\n def spam(self, x):\n "
},
{
"path": "cookbook/c08/p16_more_constructor.py",
"chars": 482,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 定义类的多个构造函数\nDesc : \n\"\"\"\n\nimport time\n\n\nclass Date:\n \"\"\"方法一:"
},
{
"path": "cookbook/c08/p17_without_init.py",
"chars": 726,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 不使用__init__方法初创建对象\nDesc : \n\"\"\"\n\n\nclass Date:\n def __init__"
},
{
"path": "cookbook/c08/p18_mixin_classes.py",
"chars": 2200,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 混入类\nDesc : 如果单独使用Minxin类没有任何意义,但是当利用多继承和其他类配合后就有神奇效果了。\n Mi"
},
{
"path": "cookbook/c08/p19_stateful_object.py",
"chars": 2924,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 实现状态对象或状态机\nDesc : \n\"\"\"\n\n\nclass Connection:\n \"\"\"普通方案,好多个判断语"
},
{
"path": "cookbook/c08/p20_invoke_bystr.py",
"chars": 729,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 通过字符串调用方法\nDesc : \n\"\"\"\n\nimport math\n\n\nclass Point:\n def __i"
},
{
"path": "cookbook/c08/p21_vistor_pattern.py",
"chars": 2770,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 观察者模式\nDesc : \n\"\"\"\n\n\nclass Node:\n pass\n\n\nclass UnaryOperato"
},
{
"path": "cookbook/c08/p22_vistor_norecursiion.py",
"chars": 2319,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 非递归的观察者模式\nDesc : \n\"\"\"\n\nimport types\n\n\nclass Node:\n pass\n\n\n"
},
{
"path": "cookbook/c08/p23_weakref.py",
"chars": 1285,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 弱引用\nDesc : \n\"\"\"\n\nimport weakref\n\n\nclass Node:\n def __init_"
},
{
"path": "cookbook/c08/p24_class_compare.py",
"chars": 1963,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 类支持比较操作\nDesc : \n\"\"\"\n\nfrom functools import total_ordering\n\n\nc"
},
{
"path": "cookbook/c08/p25_cached_objects.py",
"chars": 2429,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 创建缓存实例\nDesc :\n\"\"\"\n\nimport logging\n\na = logging.getLogger('foo"
},
{
"path": "cookbook/c09/__init__.py",
"chars": 79,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: sample\nDesc : \n\"\"\"\n\n"
},
{
"path": "cookbook/c09/p01_wrap_function.py",
"chars": 557,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 包装函数\nDesc : \n\"\"\"\n\nimport time\nfrom functools import wraps\n\n\nd"
},
{
"path": "cookbook/c09/p02_preserve_metadata.py",
"chars": 683,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 创建装饰器时保留函数元信息\nDesc : \n\"\"\"\n\nimport time\nfrom functools import "
},
{
"path": "cookbook/c09/p03_unwrap_decorator.py",
"chars": 550,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 解除包装器\nDesc : \n\"\"\"\n\nfrom functools import wraps\n\n\ndef decorato"
},
{
"path": "cookbook/c09/p04_decorator_argument.py",
"chars": 896,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 带有参数的装饰器\nDesc : \n\"\"\"\n\nfrom functools import wraps\nimport logg"
},
{
"path": "cookbook/c09/p05_adjust_attribute.py",
"chars": 2457,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 可调整属性的装饰器\nDesc : \n\"\"\"\n\nfrom functools import wraps, partial\ni"
},
{
"path": "cookbook/c09/p06_optarg_decorator.py",
"chars": 821,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 带可选参数的装饰器\nDesc : \n\"\"\"\nfrom functools import wraps, partial\nim"
},
{
"path": "cookbook/c09/p07_typecheck.py",
"chars": 1263,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 函数参数强制类型检查\nDesc : \n\"\"\"\n\nfrom inspect import signature\nfrom fu"
},
{
"path": "cookbook/c09/p08_inclass_decorator.py",
"chars": 948,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 类中定义装饰器\nDesc : \n\"\"\"\n\nfrom functools import wraps\n\nclass A:\n "
},
{
"path": "cookbook/c09/p09_class_decorator.py",
"chars": 943,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 将装饰器定义成类\nDesc : \n\"\"\"\n\nimport types\nfrom functools import wrap"
},
{
"path": "cookbook/c09/p10_static_decorator.py",
"chars": 945,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: sample\nDesc : \n\"\"\"\n\nimport time\nfrom functools import wraps\n\n"
},
{
"path": "cookbook/c09/p11_add_argument.py",
"chars": 1738,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 给被包装函数增加参数\nDesc : \n\"\"\"\n\nfrom functools import wraps\nimport in"
},
{
"path": "cookbook/c09/p12_patch_class.py",
"chars": 561,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 使用类装饰器来增强类功能\nDesc : \n\"\"\"\n\n\ndef log_getattribute(cls):\n # G"
},
{
"path": "cookbook/c09/p13_instance_create.py",
"chars": 1326,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 通过元类控制实例的创建\nDesc : \n\"\"\"\n\n\nclass NoInstances(type):\n def __"
},
{
"path": "cookbook/c09/p14_attribute_order.py",
"chars": 1486,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 类定义中属性的顺序\nDesc : \n\"\"\"\nfrom collections import OrderedDict\n\n# "
},
{
"path": "cookbook/c09/p15_meta_optional_arg.py",
"chars": 858,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 元类中的可选参数\nDesc : \n\"\"\"\n\nfrom abc import ABCMeta, abstractmethod"
},
{
"path": "cookbook/c09/p16_enforce_args.py",
"chars": 1490,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 强制*args和**kwargs的参数签名\nDesc : \n\"\"\"\n\nfrom inspect import Signat"
},
{
"path": "cookbook/c09/p17_code_convention.py",
"chars": 1945,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 强制编码规约\nDesc : \n\"\"\"\n\n\nclass MyMeta(type):\n def __init__(sel"
},
{
"path": "cookbook/c09/p18_define_classes.py",
"chars": 1284,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 以编程方式定义类\nDesc : \n\"\"\"\n\n# stock.py\n# Example of making a class "
},
{
"path": "cookbook/c09/p19_define_init.py",
"chars": 714,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 在定义的时候初始化类的成员\nDesc : \n\"\"\"\n\nimport operator\n\n\nclass StructTupl"
},
{
"path": "cookbook/c09/p20_multiple_dispatch.py",
"chars": 4362,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 利用函数注解实现方法重载\nDesc : \n\"\"\"\n\n# multiple.py\nimport inspect\nimport"
},
{
"path": "cookbook/c09/p21_avoid_repetitive.py",
"chars": 1490,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 避免重复的属性方法\nDesc : \n\"\"\"\n\n\nclass Person:\n def __init__(self, "
},
{
"path": "cookbook/c09/p22_context_manager.py",
"chars": 811,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 定义上下文管理器的简单方法\nDesc : \n\"\"\"\n\nimport time\nfrom contextlib import"
},
{
"path": "cookbook/c09/p23_local_side.py",
"chars": 323,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 在局部变量域中执行代码\nDesc : \n\"\"\"\n\ndef test3():\n x = 0\n loc = loc"
},
{
"path": "cookbook/c09/p24_analyze_source.py",
"chars": 2474,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 解析与分析Python源码\nDesc : \n\"\"\"\n\nimport ast\n\n\nclass CodeAnalyzer(as"
},
{
"path": "cookbook/c09/p25_disassemble_bytecode.py",
"chars": 584,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 拆解Python字节码\nDesc : \n\"\"\"\n\nimport opcode\n\n\ndef generate_opcodes"
},
{
"path": "cookbook/c10/__init__.py",
"chars": 79,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: sample\nDesc : \n\"\"\"\n\n"
},
{
"path": "cookbook/c10/p02_control_import.py",
"chars": 211,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 控制导入内容\nDesc : \n\"\"\"\n\n# somemodule.py\ndef spam():\n pass\n\n\nde"
},
{
"path": "cookbook/c10/p12_import_patch.py",
"chars": 1399,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: sample\nDesc : \n\"\"\"\n\nimport importlib\nimport sys\nfrom collecti"
},
{
"path": "cookbook/c11/p01_.py",
"chars": 72,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: \nDesc : \n\"\"\"\n"
},
{
"path": "cookbook/c11/p02_.py",
"chars": 72,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: \nDesc : \n\"\"\"\n"
},
{
"path": "cookbook/c11/p03_.py",
"chars": 72,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: \nDesc : \n\"\"\"\n"
},
{
"path": "cookbook/c11/p04_.py",
"chars": 72,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: \nDesc : \n\"\"\"\n"
},
{
"path": "cookbook/c11/p05_.py",
"chars": 72,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: \nDesc : \n\"\"\"\n"
},
{
"path": "cookbook/c11/p06_.py",
"chars": 72,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: \nDesc : \n\"\"\"\n"
},
{
"path": "cookbook/c11/p07_.py",
"chars": 72,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: \nDesc : \n\"\"\"\n"
},
{
"path": "cookbook/c11/p08_.py",
"chars": 72,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: \nDesc : \n\"\"\"\n"
},
{
"path": "cookbook/c11/p09_.py",
"chars": 72,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: \nDesc : \n\"\"\"\n"
},
{
"path": "cookbook/c11/p10_.py",
"chars": 72,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: \nDesc : \n\"\"\"\n"
},
{
"path": "cookbook/c11/p11_.py",
"chars": 72,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: \nDesc : \n\"\"\"\n"
},
{
"path": "cookbook/c11/p12_.py",
"chars": 72,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: \nDesc : \n\"\"\"\n"
},
{
"path": "cookbook/c11/p13_.py",
"chars": 72,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: \nDesc : \n\"\"\"\n"
},
{
"path": "cookbook/c12/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "cookbook/c12/p01_start_stop_thread.py",
"chars": 1613,
"preview": "import socket\nimport time\n\ndef countdown(n):\n while n > 0:\n print('T-minus', n)\n n -= 1\n time.sl"
},
{
"path": "cookbook/c12/p02_.py",
"chars": 72,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: \nDesc : \n\"\"\"\n"
},
{
"path": "cookbook/c12/p03_.py",
"chars": 72,
"preview": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: \nDesc : \n\"\"\"\n"
}
]
// ... and 627 more files (download for full content)
About this extraction
This page contains the full source code of the yidao620c/python3-cookbook GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 827 files (6.2 MB), approximately 1.7M tokens, and a symbol index with 848 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.