sequence
stringlengths
546
16.2k
code
stringlengths
108
19.3k
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:formatFlow; 3, parameters; 3, 4; 4, identifier:s; 5, block; 5, 6; 5, 8; 5, 12; 5, 16; 5, 17; 5, 21; 5, 22; 5, 26; 5, 79; 5, 88; 5, 249; 6, expression_statement; 6, 7; 7, comment; 8, expression_statement; 8, 9; 9, assignment; 9, 10; 9, 11; 10, identifier:result; 11, string:""; 12, expression_statement; 12, 13; 13, assignment; 13, 14; 13, 15; 14, identifier:shifts; 15, list:[]; 16, comment; 17, expression_statement; 17, 18; 18, assignment; 18, 19; 18, 20; 19, identifier:pos; 20, integer:0; 21, comment; 22, expression_statement; 22, 23; 23, assignment; 23, 24; 23, 25; 24, identifier:nextIsList; 25, False; 26, function_definition; 26, 27; 26, 28; 26, 32; 27, function_name:IsNextList; 28, parameters; 28, 29; 28, 30; 28, 31; 29, identifier:index; 30, identifier:maxIndex; 31, identifier:buf; 32, block; 32, 33; 32, 40; 32, 51; 32, 77; 33, if_statement; 33, 34; 33, 37; 34, comparison_operator:==; 34, 35; 34, 36; 35, identifier:index; 36, identifier:maxIndex; 37, block; 37, 38; 38, return_statement; 38, 39; 39, False; 40, if_statement; 40, 41; 40, 48; 41, comparison_operator:==; 41, 42; 41, 47; 42, subscript; 42, 43; 42, 44; 43, identifier:buf; 44, binary_operator:+; 44, 45; 44, 46; 45, identifier:index; 46, integer:1; 47, string:'<'; 48, block; 48, 49; 49, return_statement; 49, 50; 50, True; 51, if_statement; 51, 52; 51, 57; 52, comparison_operator:<; 52, 53; 52, 54; 53, identifier:index; 54, binary_operator:-; 54, 55; 54, 56; 55, identifier:maxIndex; 56, integer:1; 57, block; 57, 58; 58, if_statement; 58, 59; 58, 74; 59, boolean_operator:and; 59, 60; 59, 67; 60, comparison_operator:==; 60, 61; 60, 66; 61, subscript; 61, 62; 61, 63; 62, identifier:buf; 63, binary_operator:+; 63, 64; 63, 65; 64, identifier:index; 65, integer:1; 66, string:'\n'; 67, comparison_operator:==; 67, 68; 67, 73; 68, subscript; 68, 69; 68, 70; 69, identifier:buf; 70, binary_operator:+; 70, 71; 70, 72; 71, identifier:index; 72, integer:2; 73, string:'<'; 74, block; 74, 75; 75, return_statement; 75, 76; 76, True; 77, return_statement; 77, 78; 78, False; 79, expression_statement; 79, 80; 80, assignment; 80, 81; 80, 82; 81, identifier:maxIndex; 82, binary_operator:-; 82, 83; 82, 87; 83, call; 83, 84; 83, 85; 84, identifier:len; 85, argument_list; 85, 86; 86, identifier:s; 87, integer:1; 88, for_statement; 88, 89; 88, 90; 88, 97; 89, identifier:index; 90, call; 90, 91; 90, 92; 91, identifier:range; 92, argument_list; 92, 93; 93, call; 93, 94; 93, 95; 94, identifier:len; 95, argument_list; 95, 96; 96, identifier:s; 97, block; 97, 98; 97, 104; 97, 151; 97, 183; 97, 241; 97, 245; 98, expression_statement; 98, 99; 99, assignment; 99, 100; 99, 101; 100, identifier:sym; 101, subscript; 101, 102; 101, 103; 102, identifier:s; 103, identifier:index; 104, if_statement; 104, 105; 104, 108; 105, comparison_operator:==; 105, 106; 105, 107; 106, identifier:sym; 107, string:"\n"; 108, block; 108, 109; 108, 116; 108, 124; 108, 128; 108, 150; 109, expression_statement; 109, 110; 110, assignment; 110, 111; 110, 112; 111, identifier:lastShift; 112, subscript; 112, 113; 112, 114; 113, identifier:shifts; 114, unary_operator:-; 114, 115; 115, integer:1; 116, expression_statement; 116, 117; 117, augmented_assignment:+=; 117, 118; 117, 119; 118, identifier:result; 119, binary_operator:+; 119, 120; 119, 121; 120, identifier:sym; 121, binary_operator:*; 121, 122; 121, 123; 122, identifier:lastShift; 123, string:" "; 124, expression_statement; 124, 125; 125, assignment; 125, 126; 125, 127; 126, identifier:pos; 127, identifier:lastShift; 128, if_statement; 128, 129; 128, 132; 129, comparison_operator:<; 129, 130; 129, 131; 130, identifier:index; 131, identifier:maxIndex; 132, block; 132, 133; 133, if_statement; 133, 134; 133, 141; 134, comparison_operator:not; 134, 135; 134, 140; 135, subscript; 135, 136; 135, 137; 136, identifier:s; 137, binary_operator:+; 137, 138; 137, 139; 138, identifier:index; 139, integer:1; 140, string:"<>"; 141, block; 141, 142; 141, 146; 142, expression_statement; 142, 143; 143, augmented_assignment:+=; 143, 144; 143, 145; 144, identifier:result; 145, string:" "; 146, expression_statement; 146, 147; 147, augmented_assignment:+=; 147, 148; 147, 149; 148, identifier:pos; 149, integer:1; 150, continue_statement; 151, if_statement; 151, 152; 151, 155; 152, comparison_operator:==; 152, 153; 152, 154; 153, identifier:sym; 154, string:"<"; 155, block; 155, 156; 155, 174; 155, 178; 155, 182; 156, if_statement; 156, 157; 156, 160; 156, 168; 157, comparison_operator:==; 157, 158; 157, 159; 158, identifier:nextIsList; 159, False; 160, block; 160, 161; 161, expression_statement; 161, 162; 162, call; 162, 163; 162, 166; 163, attribute; 163, 164; 163, 165; 164, identifier:shifts; 165, identifier:append; 166, argument_list; 166, 167; 167, identifier:pos; 168, else_clause; 168, 169; 169, block; 169, 170; 170, expression_statement; 170, 171; 171, assignment; 171, 172; 171, 173; 172, identifier:nextIsList; 173, False; 174, expression_statement; 174, 175; 175, augmented_assignment:+=; 175, 176; 175, 177; 176, identifier:pos; 177, integer:1; 178, expression_statement; 178, 179; 179, augmented_assignment:+=; 179, 180; 179, 181; 180, identifier:result; 181, identifier:sym; 182, continue_statement; 183, if_statement; 183, 184; 183, 187; 184, comparison_operator:==; 184, 185; 184, 186; 185, identifier:sym; 186, string:">"; 187, block; 187, 188; 187, 195; 187, 199; 187, 205; 187, 209; 187, 213; 187, 217; 187, 240; 188, expression_statement; 188, 189; 189, assignment; 189, 190; 189, 191; 190, identifier:shift; 191, subscript; 191, 192; 191, 193; 192, identifier:shifts; 193, unary_operator:-; 193, 194; 194, integer:1; 195, expression_statement; 195, 196; 196, augmented_assignment:+=; 196, 197; 196, 198; 197, identifier:result; 198, string:'\n'; 199, expression_statement; 199, 200; 200, augmented_assignment:+=; 200, 201; 200, 202; 201, identifier:result; 202, binary_operator:*; 202, 203; 202, 204; 203, identifier:shift; 204, string:" "; 205, expression_statement; 205, 206; 206, assignment; 206, 207; 206, 208; 207, identifier:pos; 208, identifier:shift; 209, expression_statement; 209, 210; 210, augmented_assignment:+=; 210, 211; 210, 212; 211, identifier:result; 212, identifier:sym; 213, expression_statement; 213, 214; 214, augmented_assignment:+=; 214, 215; 214, 216; 215, identifier:pos; 216, integer:1; 217, if_statement; 217, 218; 217, 224; 217, 229; 218, call; 218, 219; 218, 220; 219, identifier:IsNextList; 220, argument_list; 220, 221; 220, 222; 220, 223; 221, identifier:index; 222, identifier:maxIndex; 223, identifier:s; 224, block; 224, 225; 225, expression_statement; 225, 226; 226, assignment; 226, 227; 226, 228; 227, identifier:nextIsList; 228, True; 229, else_clause; 229, 230; 230, block; 230, 231; 230, 236; 231, delete_statement; 231, 232; 232, subscript; 232, 233; 232, 234; 233, identifier:shifts; 234, unary_operator:-; 234, 235; 235, integer:1; 236, expression_statement; 236, 237; 237, assignment; 237, 238; 237, 239; 238, identifier:nextIsList; 239, False; 240, continue_statement; 241, expression_statement; 241, 242; 242, augmented_assignment:+=; 242, 243; 242, 244; 243, identifier:result; 244, identifier:sym; 245, expression_statement; 245, 246; 246, augmented_assignment:+=; 246, 247; 246, 248; 247, identifier:pos; 248, integer:1; 249, return_statement; 249, 250; 250, identifier:result
def formatFlow(s): """Reformats the control flow output""" result = "" shifts = [] # positions of opening '<' pos = 0 # symbol position in a line nextIsList = False def IsNextList(index, maxIndex, buf): if index == maxIndex: return False if buf[index + 1] == '<': return True if index < maxIndex - 1: if buf[index + 1] == '\n' and buf[index + 2] == '<': return True return False maxIndex = len(s) - 1 for index in range(len(s)): sym = s[index] if sym == "\n": lastShift = shifts[-1] result += sym + lastShift * " " pos = lastShift if index < maxIndex: if s[index + 1] not in "<>": result += " " pos += 1 continue if sym == "<": if nextIsList == False: shifts.append(pos) else: nextIsList = False pos += 1 result += sym continue if sym == ">": shift = shifts[-1] result += '\n' result += shift * " " pos = shift result += sym pos += 1 if IsNextList(index, maxIndex, s): nextIsList = True else: del shifts[-1] nextIsList = False continue result += sym pos += 1 return result
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 9; 2, function_name:train; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:self; 5, identifier:training_set; 6, default_parameter; 6, 7; 6, 8; 7, identifier:iterations; 8, integer:500; 9, block; 9, 10; 9, 12; 9, 179; 9, 191; 9, 203; 9, 212; 9, 223; 9, 234; 9, 238; 9, 313; 9, 322; 10, expression_statement; 10, 11; 11, comment; 12, if_statement; 12, 13; 12, 19; 12, 101; 13, comparison_operator:>; 13, 14; 13, 18; 14, call; 14, 15; 14, 16; 15, identifier:len; 16, argument_list; 16, 17; 17, identifier:training_set; 18, integer:2; 19, block; 19, 20; 19, 37; 20, expression_statement; 20, 21; 21, assignment; 21, 22; 21, 25; 22, attribute; 22, 23; 22, 24; 23, identifier:self; 24, identifier:__X; 25, call; 25, 26; 25, 29; 26, attribute; 26, 27; 26, 28; 27, identifier:np; 28, identifier:matrix; 29, argument_list; 29, 30; 30, list_comprehension; 30, 31; 30, 34; 31, subscript; 31, 32; 31, 33; 32, identifier:example; 33, integer:0; 34, for_in_clause; 34, 35; 34, 36; 35, identifier:example; 36, identifier:training_set; 37, if_statement; 37, 38; 37, 43; 37, 69; 38, comparison_operator:==; 38, 39; 38, 42; 39, attribute; 39, 40; 39, 41; 40, identifier:self; 41, identifier:__num_labels; 42, integer:1; 43, block; 43, 44; 44, expression_statement; 44, 45; 45, assignment; 45, 46; 45, 49; 46, attribute; 46, 47; 46, 48; 47, identifier:self; 48, identifier:__y; 49, call; 49, 50; 49, 64; 50, attribute; 50, 51; 50, 63; 51, call; 51, 52; 51, 55; 52, attribute; 52, 53; 52, 54; 53, identifier:np; 54, identifier:matrix; 55, argument_list; 55, 56; 56, list_comprehension; 56, 57; 56, 60; 57, subscript; 57, 58; 57, 59; 58, identifier:example; 59, integer:1; 60, for_in_clause; 60, 61; 60, 62; 61, identifier:example; 62, identifier:training_set; 63, identifier:reshape; 64, argument_list; 64, 65; 65, tuple; 65, 66; 65, 68; 66, unary_operator:-; 66, 67; 67, integer:1; 68, integer:1; 69, else_clause; 69, 70; 70, block; 70, 71; 70, 82; 71, expression_statement; 71, 72; 72, assignment; 72, 73; 72, 74; 73, identifier:eye; 74, call; 74, 75; 74, 78; 75, attribute; 75, 76; 75, 77; 76, identifier:np; 77, identifier:eye; 78, argument_list; 78, 79; 79, attribute; 79, 80; 79, 81; 80, identifier:self; 81, identifier:__num_labels; 82, expression_statement; 82, 83; 83, assignment; 83, 84; 83, 87; 84, attribute; 84, 85; 84, 86; 85, identifier:self; 86, identifier:__y; 87, call; 87, 88; 87, 91; 88, attribute; 88, 89; 88, 90; 89, identifier:np; 90, identifier:matrix; 91, argument_list; 91, 92; 92, list_comprehension; 92, 93; 92, 98; 93, subscript; 93, 94; 93, 95; 94, identifier:eye; 95, subscript; 95, 96; 95, 97; 96, identifier:example; 97, integer:1; 98, for_in_clause; 98, 99; 98, 100; 99, identifier:example; 100, identifier:training_set; 101, else_clause; 101, 102; 102, block; 102, 103; 102, 116; 103, expression_statement; 103, 104; 104, assignment; 104, 105; 104, 108; 105, attribute; 105, 106; 105, 107; 106, identifier:self; 107, identifier:__X; 108, call; 108, 109; 108, 112; 109, attribute; 109, 110; 109, 111; 110, identifier:np; 111, identifier:matrix; 112, argument_list; 112, 113; 113, subscript; 113, 114; 113, 115; 114, identifier:training_set; 115, integer:0; 116, if_statement; 116, 117; 116, 122; 116, 144; 117, comparison_operator:==; 117, 118; 117, 121; 118, attribute; 118, 119; 118, 120; 119, identifier:self; 120, identifier:__num_labels; 121, integer:1; 122, block; 122, 123; 123, expression_statement; 123, 124; 124, assignment; 124, 125; 124, 128; 125, attribute; 125, 126; 125, 127; 126, identifier:self; 127, identifier:__y; 128, call; 128, 129; 128, 139; 129, attribute; 129, 130; 129, 138; 130, call; 130, 131; 130, 134; 131, attribute; 131, 132; 131, 133; 132, identifier:np; 133, identifier:matrix; 134, argument_list; 134, 135; 135, subscript; 135, 136; 135, 137; 136, identifier:training_set; 137, integer:1; 138, identifier:reshape; 139, argument_list; 139, 140; 140, tuple; 140, 141; 140, 143; 141, unary_operator:-; 141, 142; 142, integer:1; 143, integer:1; 144, else_clause; 144, 145; 145, block; 145, 146; 145, 157; 146, expression_statement; 146, 147; 147, assignment; 147, 148; 147, 149; 148, identifier:eye; 149, call; 149, 150; 149, 153; 150, attribute; 150, 151; 150, 152; 151, identifier:np; 152, identifier:eye; 153, argument_list; 153, 154; 154, attribute; 154, 155; 154, 156; 155, identifier:self; 156, identifier:__num_labels; 157, expression_statement; 157, 158; 158, assignment; 158, 159; 158, 162; 159, attribute; 159, 160; 159, 161; 160, identifier:self; 161, identifier:__y; 162, call; 162, 163; 162, 166; 163, attribute; 163, 164; 163, 165; 164, identifier:np; 165, identifier:matrix; 166, argument_list; 166, 167; 167, list_comprehension; 167, 168; 167, 171; 167, 176; 168, subscript; 168, 169; 168, 170; 169, identifier:eye; 170, identifier:index; 171, for_in_clause; 171, 172; 171, 173; 172, identifier:sublist; 173, subscript; 173, 174; 173, 175; 174, identifier:training_set; 175, integer:1; 176, for_in_clause; 176, 177; 176, 178; 177, identifier:index; 178, identifier:sublist; 179, expression_statement; 179, 180; 180, assignment; 180, 181; 180, 184; 181, attribute; 181, 182; 181, 183; 182, identifier:self; 183, identifier:__m; 184, subscript; 184, 185; 184, 190; 185, attribute; 185, 186; 185, 189; 186, attribute; 186, 187; 186, 188; 187, identifier:self; 188, identifier:__X; 189, identifier:shape; 190, integer:0; 191, expression_statement; 191, 192; 192, assignment; 192, 193; 192, 196; 193, attribute; 193, 194; 193, 195; 194, identifier:self; 195, identifier:__input_layer_size; 196, subscript; 196, 197; 196, 202; 197, attribute; 197, 198; 197, 201; 198, attribute; 198, 199; 198, 200; 199, identifier:self; 200, identifier:__X; 201, identifier:shape; 202, integer:1; 203, expression_statement; 203, 204; 204, assignment; 204, 205; 204, 208; 205, attribute; 205, 206; 205, 207; 206, identifier:self; 207, identifier:__sizes; 208, list:[self.__input_layer_size]; 208, 209; 209, attribute; 209, 210; 209, 211; 210, identifier:self; 211, identifier:__input_layer_size; 212, expression_statement; 212, 213; 213, call; 213, 214; 213, 219; 214, attribute; 214, 215; 214, 218; 215, attribute; 215, 216; 215, 217; 216, identifier:self; 217, identifier:__sizes; 218, identifier:extend; 219, argument_list; 219, 220; 220, attribute; 220, 221; 220, 222; 221, identifier:self; 222, identifier:__hidden_layers; 223, expression_statement; 223, 224; 224, call; 224, 225; 224, 230; 225, attribute; 225, 226; 225, 229; 226, attribute; 226, 227; 226, 228; 227, identifier:self; 228, identifier:__sizes; 229, identifier:append; 230, argument_list; 230, 231; 231, attribute; 231, 232; 231, 233; 232, identifier:self; 233, identifier:__num_labels; 234, expression_statement; 234, 235; 235, assignment; 235, 236; 235, 237; 236, identifier:initial_theta; 237, list:[]; 238, for_statement; 238, 239; 238, 240; 238, 251; 239, identifier:count; 240, call; 240, 241; 240, 242; 241, identifier:range; 242, argument_list; 242, 243; 243, binary_operator:-; 243, 244; 243, 250; 244, call; 244, 245; 244, 246; 245, identifier:len; 246, argument_list; 246, 247; 247, attribute; 247, 248; 247, 249; 248, identifier:self; 249, identifier:__sizes; 250, integer:1; 251, block; 251, 252; 251, 280; 252, expression_statement; 252, 253; 253, assignment; 253, 254; 253, 255; 254, identifier:epsilon; 255, binary_operator:/; 255, 256; 255, 262; 256, call; 256, 257; 256, 260; 257, attribute; 257, 258; 257, 259; 258, identifier:np; 259, identifier:sqrt; 260, argument_list; 260, 261; 261, integer:6; 262, call; 262, 263; 262, 266; 263, attribute; 263, 264; 263, 265; 264, identifier:np; 265, identifier:sqrt; 266, argument_list; 266, 267; 267, binary_operator:+; 267, 268; 267, 273; 268, subscript; 268, 269; 268, 272; 269, attribute; 269, 270; 269, 271; 270, identifier:self; 271, identifier:__sizes; 272, identifier:count; 273, subscript; 273, 274; 273, 277; 274, attribute; 274, 275; 274, 276; 275, identifier:self; 276, identifier:__sizes; 277, binary_operator:+; 277, 278; 277, 279; 278, identifier:count; 279, integer:1; 280, expression_statement; 280, 281; 281, call; 281, 282; 281, 285; 282, attribute; 282, 283; 282, 284; 283, identifier:initial_theta; 284, identifier:append; 285, argument_list; 285, 286; 286, binary_operator:-; 286, 287; 286, 312; 287, binary_operator:*; 287, 288; 287, 311; 288, binary_operator:*; 288, 289; 288, 310; 289, call; 289, 290; 289, 295; 290, attribute; 290, 291; 290, 294; 291, attribute; 291, 292; 291, 293; 292, identifier:np; 293, identifier:random; 294, identifier:rand; 295, argument_list; 295, 296; 295, 303; 296, subscript; 296, 297; 296, 300; 297, attribute; 297, 298; 297, 299; 298, identifier:self; 299, identifier:__sizes; 300, binary_operator:+; 300, 301; 300, 302; 301, identifier:count; 302, integer:1; 303, binary_operator:+; 303, 304; 303, 309; 304, subscript; 304, 305; 304, 308; 305, attribute; 305, 306; 305, 307; 306, identifier:self; 307, identifier:__sizes; 308, identifier:count; 309, integer:1; 310, integer:2; 311, identifier:epsilon; 312, identifier:epsilon; 313, expression_statement; 313, 314; 314, assignment; 314, 315; 314, 316; 315, identifier:initial_theta; 316, call; 316, 317; 316, 320; 317, attribute; 317, 318; 317, 319; 318, identifier:self; 319, identifier:__unroll; 320, argument_list; 320, 321; 321, identifier:initial_theta; 322, expression_statement; 322, 323; 323, assignment; 323, 324; 323, 327; 324, attribute; 324, 325; 324, 326; 325, identifier:self; 326, identifier:__thetas; 327, call; 327, 328; 327, 331; 328, attribute; 328, 329; 328, 330; 329, identifier:self; 330, identifier:__roll; 331, argument_list; 331, 332; 332, call; 332, 333; 332, 334; 333, identifier:fmin_bfgs; 334, argument_list; 334, 335; 334, 338; 334, 339; 334, 344; 335, attribute; 335, 336; 335, 337; 336, identifier:self; 337, identifier:__cost_function; 338, identifier:initial_theta; 339, keyword_argument; 339, 340; 339, 341; 340, identifier:fprime; 341, attribute; 341, 342; 341, 343; 342, identifier:self; 343, identifier:__cost_grad_function; 344, keyword_argument; 344, 345; 344, 346; 345, identifier:maxiter; 346, identifier:iterations
def train(self, training_set, iterations=500): """Trains itself using the sequence data.""" if len(training_set) > 2: self.__X = np.matrix([example[0] for example in training_set]) if self.__num_labels == 1: self.__y = np.matrix([example[1] for example in training_set]).reshape((-1, 1)) else: eye = np.eye(self.__num_labels) self.__y = np.matrix([eye[example[1]] for example in training_set]) else: self.__X = np.matrix(training_set[0]) if self.__num_labels == 1: self.__y = np.matrix(training_set[1]).reshape((-1, 1)) else: eye = np.eye(self.__num_labels) self.__y = np.matrix([eye[index] for sublist in training_set[1] for index in sublist]) self.__m = self.__X.shape[0] self.__input_layer_size = self.__X.shape[1] self.__sizes = [self.__input_layer_size] self.__sizes.extend(self.__hidden_layers) self.__sizes.append(self.__num_labels) initial_theta = [] for count in range(len(self.__sizes) - 1): epsilon = np.sqrt(6) / np.sqrt(self.__sizes[count]+self.__sizes[count+1]) initial_theta.append(np.random.rand(self.__sizes[count+1],self.__sizes[count]+1)*2*epsilon-epsilon) initial_theta = self.__unroll(initial_theta) self.__thetas = self.__roll(fmin_bfgs(self.__cost_function, initial_theta, fprime=self.__cost_grad_function, maxiter=iterations))
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 8; 2, function_name:__cost; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 7; 4, identifier:self; 5, identifier:params; 6, identifier:phase; 7, identifier:X; 8, block; 8, 9; 8, 11; 8, 20; 8, 45; 8, 46; 8, 51; 8, 52; 8, 57; 8, 58; 8, 145; 8, 180; 8, 232; 8, 233; 8, 283; 8, 290; 8, 294; 8, 298; 8, 458; 8, 470; 9, expression_statement; 9, 10; 10, comment; 11, expression_statement; 11, 12; 12, assignment; 12, 13; 12, 14; 13, identifier:params; 14, call; 14, 15; 14, 18; 15, attribute; 15, 16; 15, 17; 16, identifier:self; 17, identifier:__roll; 18, argument_list; 18, 19; 19, identifier:params; 20, expression_statement; 20, 21; 21, assignment; 21, 22; 21, 23; 22, identifier:a; 23, call; 23, 24; 23, 27; 24, attribute; 24, 25; 24, 26; 25, identifier:np; 26, identifier:concatenate; 27, argument_list; 27, 28; 27, 42; 28, tuple; 28, 29; 28, 41; 29, call; 29, 30; 29, 33; 30, attribute; 30, 31; 30, 32; 31, identifier:np; 32, identifier:ones; 33, argument_list; 33, 34; 34, tuple; 34, 35; 34, 40; 35, subscript; 35, 36; 35, 39; 36, attribute; 36, 37; 36, 38; 37, identifier:X; 38, identifier:shape; 39, integer:0; 40, integer:1; 41, identifier:X; 42, keyword_argument; 42, 43; 42, 44; 43, identifier:axis; 44, integer:1; 45, comment; 46, expression_statement; 46, 47; 47, assignment; 47, 48; 47, 49; 48, identifier:calculated_a; 49, list:[a]; 49, 50; 50, identifier:a; 51, comment; 52, expression_statement; 52, 53; 53, assignment; 53, 54; 53, 55; 54, identifier:calculated_z; 55, list:[0]; 55, 56; 56, integer:0; 57, comment; 58, for_statement; 58, 59; 58, 62; 58, 66; 58, 67; 59, pattern_list; 59, 60; 59, 61; 60, identifier:i; 61, identifier:theta; 62, call; 62, 63; 62, 64; 63, identifier:enumerate; 64, argument_list; 64, 65; 65, identifier:params; 66, comment; 67, block; 67, 68; 67, 81; 67, 82; 67, 89; 67, 90; 67, 99; 67, 100; 67, 137; 67, 144; 68, expression_statement; 68, 69; 69, assignment; 69, 70; 69, 71; 70, identifier:z; 71, binary_operator:*; 71, 72; 71, 76; 72, subscript; 72, 73; 72, 74; 73, identifier:calculated_a; 74, unary_operator:-; 74, 75; 75, integer:1; 76, call; 76, 77; 76, 80; 77, attribute; 77, 78; 77, 79; 78, identifier:theta; 79, identifier:transpose; 80, argument_list; 81, comment; 82, expression_statement; 82, 83; 83, call; 83, 84; 83, 87; 84, attribute; 84, 85; 84, 86; 85, identifier:calculated_z; 86, identifier:append; 87, argument_list; 87, 88; 88, identifier:z; 89, comment; 90, expression_statement; 90, 91; 91, assignment; 91, 92; 91, 93; 92, identifier:a; 93, call; 93, 94; 93, 97; 94, attribute; 94, 95; 94, 96; 95, identifier:self; 96, identifier:sigmoid; 97, argument_list; 97, 98; 98, identifier:z; 99, comment; 100, if_statement; 100, 101; 100, 109; 100, 110; 101, comparison_operator:!=; 101, 102; 101, 103; 102, identifier:i; 103, binary_operator:-; 103, 104; 103, 108; 104, call; 104, 105; 104, 106; 105, identifier:len; 106, argument_list; 106, 107; 107, identifier:params; 108, integer:1; 109, comment; 110, block; 110, 111; 110, 136; 111, expression_statement; 111, 112; 112, assignment; 112, 113; 112, 114; 113, identifier:a; 114, call; 114, 115; 114, 118; 115, attribute; 115, 116; 115, 117; 116, identifier:np; 117, identifier:concatenate; 118, argument_list; 118, 119; 118, 133; 119, tuple; 119, 120; 119, 132; 120, call; 120, 121; 120, 124; 121, attribute; 121, 122; 121, 123; 122, identifier:np; 123, identifier:ones; 124, argument_list; 124, 125; 125, tuple; 125, 126; 125, 131; 126, subscript; 126, 127; 126, 130; 127, attribute; 127, 128; 127, 129; 128, identifier:a; 129, identifier:shape; 130, integer:0; 131, integer:1; 132, identifier:a; 133, keyword_argument; 133, 134; 133, 135; 134, identifier:axis; 135, integer:1; 136, comment; 137, expression_statement; 137, 138; 138, call; 138, 139; 138, 142; 139, attribute; 139, 140; 139, 141; 140, identifier:calculated_a; 141, identifier:append; 142, argument_list; 142, 143; 143, identifier:a; 144, comment; 145, if_statement; 145, 146; 145, 149; 146, comparison_operator:==; 146, 147; 146, 148; 147, identifier:phase; 148, integer:0; 149, block; 149, 150; 149, 170; 150, if_statement; 150, 151; 150, 156; 151, comparison_operator:>; 151, 152; 151, 155; 152, attribute; 152, 153; 152, 154; 153, identifier:self; 154, identifier:__num_labels; 155, integer:1; 156, block; 156, 157; 157, return_statement; 157, 158; 158, call; 158, 159; 158, 162; 159, attribute; 159, 160; 159, 161; 160, identifier:np; 161, identifier:argmax; 162, argument_list; 162, 163; 162, 167; 163, subscript; 163, 164; 163, 165; 164, identifier:calculated_a; 165, unary_operator:-; 165, 166; 166, integer:1; 167, keyword_argument; 167, 168; 167, 169; 168, identifier:axis; 169, integer:1; 170, return_statement; 170, 171; 171, call; 171, 172; 171, 175; 172, attribute; 172, 173; 172, 174; 173, identifier:np; 174, identifier:round; 175, argument_list; 175, 176; 176, subscript; 176, 177; 176, 178; 177, identifier:calculated_a; 178, unary_operator:-; 178, 179; 179, integer:1; 180, expression_statement; 180, 181; 181, assignment; 181, 182; 181, 183; 182, identifier:J; 183, binary_operator:/; 183, 184; 183, 229; 184, call; 184, 185; 184, 188; 185, attribute; 185, 186; 185, 187; 186, identifier:np; 187, identifier:sum; 188, argument_list; 188, 189; 189, binary_operator:-; 189, 190; 189, 208; 190, unary_operator:-; 190, 191; 191, call; 191, 192; 191, 195; 192, attribute; 192, 193; 192, 194; 193, identifier:np; 194, identifier:multiply; 195, argument_list; 195, 196; 195, 199; 196, attribute; 196, 197; 196, 198; 197, identifier:self; 198, identifier:__y; 199, call; 199, 200; 199, 203; 200, attribute; 200, 201; 200, 202; 201, identifier:np; 202, identifier:log; 203, argument_list; 203, 204; 204, subscript; 204, 205; 204, 206; 205, identifier:calculated_a; 206, unary_operator:-; 206, 207; 207, integer:1; 208, call; 208, 209; 208, 212; 209, attribute; 209, 210; 209, 211; 210, identifier:np; 211, identifier:multiply; 212, argument_list; 212, 213; 212, 218; 213, binary_operator:-; 213, 214; 213, 215; 214, integer:1; 215, attribute; 215, 216; 215, 217; 216, identifier:self; 217, identifier:__y; 218, call; 218, 219; 218, 222; 219, attribute; 219, 220; 219, 221; 220, identifier:np; 221, identifier:log; 222, argument_list; 222, 223; 223, binary_operator:-; 223, 224; 223, 225; 224, integer:1; 225, subscript; 225, 226; 225, 227; 226, identifier:calculated_a; 227, unary_operator:-; 227, 228; 228, integer:1; 229, attribute; 229, 230; 229, 231; 230, identifier:self; 231, identifier:__m; 232, comment; 233, if_statement; 233, 234; 233, 239; 233, 240; 234, comparison_operator:!=; 234, 235; 234, 238; 235, attribute; 235, 236; 235, 237; 236, identifier:self; 237, identifier:__lambda; 238, integer:0; 239, comment; 240, block; 240, 241; 240, 282; 241, expression_statement; 241, 242; 242, augmented_assignment:+=; 242, 243; 242, 244; 243, identifier:J; 244, binary_operator:/; 244, 245; 244, 276; 245, binary_operator:*; 245, 246; 245, 273; 246, call; 246, 247; 246, 250; 247, attribute; 247, 248; 247, 249; 248, identifier:np; 249, identifier:sum; 250, argument_list; 250, 251; 251, list_comprehension; 251, 252; 251, 270; 252, call; 252, 253; 252, 256; 253, attribute; 253, 254; 253, 255; 254, identifier:np; 255, identifier:sum; 256, argument_list; 256, 257; 257, call; 257, 258; 257, 261; 258, attribute; 258, 259; 258, 260; 259, identifier:np; 260, identifier:power; 261, argument_list; 261, 262; 261, 269; 262, subscript; 262, 263; 262, 264; 262, 266; 263, identifier:theta; 264, slice; 264, 265; 265, colon; 266, slice; 266, 267; 266, 268; 267, integer:1; 268, colon; 269, integer:2; 270, for_in_clause; 270, 271; 270, 272; 271, identifier:theta; 272, identifier:params; 273, attribute; 273, 274; 273, 275; 274, identifier:self; 275, identifier:__lambda; 276, parenthesized_expression; 276, 277; 277, binary_operator:*; 277, 278; 277, 279; 278, float:2.0; 279, attribute; 279, 280; 279, 281; 280, identifier:self; 281, identifier:__m; 282, comment; 283, if_statement; 283, 284; 283, 287; 284, comparison_operator:==; 284, 285; 284, 286; 285, identifier:phase; 286, integer:1; 287, block; 287, 288; 288, return_statement; 288, 289; 289, identifier:J; 290, expression_statement; 290, 291; 291, assignment; 291, 292; 291, 293; 292, identifier:reversed_d; 293, list:[]; 294, expression_statement; 294, 295; 295, assignment; 295, 296; 295, 297; 296, identifier:reversed_theta_grad; 297, list:[]; 298, for_statement; 298, 299; 298, 300; 298, 307; 298, 308; 299, identifier:i; 300, call; 300, 301; 300, 302; 301, identifier:range; 302, argument_list; 302, 303; 303, call; 303, 304; 303, 305; 304, identifier:len; 305, argument_list; 305, 306; 306, identifier:params; 307, comment; 308, block; 308, 309; 308, 365; 308, 372; 308, 394; 308, 451; 309, if_statement; 309, 310; 309, 313; 309, 314; 309, 327; 310, comparison_operator:==; 310, 311; 310, 312; 311, identifier:i; 312, integer:0; 313, comment; 314, block; 314, 315; 314, 326; 315, expression_statement; 315, 316; 316, assignment; 316, 317; 316, 318; 317, identifier:d; 318, binary_operator:-; 318, 319; 318, 323; 319, subscript; 319, 320; 319, 321; 320, identifier:calculated_a; 321, unary_operator:-; 321, 322; 322, integer:1; 323, attribute; 323, 324; 323, 325; 324, identifier:self; 325, identifier:__y; 326, comment; 327, else_clause; 327, 328; 327, 329; 328, comment; 329, block; 329, 330; 329, 364; 330, expression_statement; 330, 331; 331, assignment; 331, 332; 331, 333; 332, identifier:d; 333, call; 333, 334; 333, 337; 334, attribute; 334, 335; 334, 336; 335, identifier:np; 336, identifier:multiply; 337, argument_list; 337, 338; 337, 353; 338, binary_operator:*; 338, 339; 338, 343; 339, subscript; 339, 340; 339, 341; 340, identifier:reversed_d; 341, unary_operator:-; 341, 342; 342, integer:1; 343, subscript; 343, 344; 343, 348; 343, 350; 344, subscript; 344, 345; 344, 346; 345, identifier:params; 346, unary_operator:-; 346, 347; 347, identifier:i; 348, slice; 348, 349; 349, colon; 350, slice; 350, 351; 350, 352; 351, integer:1; 352, colon; 353, call; 353, 354; 353, 357; 354, attribute; 354, 355; 354, 356; 355, identifier:self; 356, identifier:sigmoid_grad; 357, argument_list; 357, 358; 358, subscript; 358, 359; 358, 360; 359, identifier:calculated_z; 360, binary_operator:-; 360, 361; 360, 363; 361, unary_operator:-; 361, 362; 362, integer:1; 363, identifier:i; 364, comment; 365, expression_statement; 365, 366; 366, call; 366, 367; 366, 370; 367, attribute; 367, 368; 367, 369; 368, identifier:reversed_d; 369, identifier:append; 370, argument_list; 370, 371; 371, identifier:d; 372, expression_statement; 372, 373; 373, assignment; 373, 374; 373, 375; 374, identifier:theta_grad; 375, binary_operator:/; 375, 376; 375, 391; 376, binary_operator:*; 376, 377; 376, 385; 377, call; 377, 378; 377, 384; 378, attribute; 378, 379; 378, 383; 379, subscript; 379, 380; 379, 381; 380, identifier:reversed_d; 381, unary_operator:-; 381, 382; 382, integer:1; 383, identifier:transpose; 384, argument_list; 385, subscript; 385, 386; 385, 387; 386, identifier:calculated_a; 387, binary_operator:-; 387, 388; 387, 390; 388, unary_operator:-; 388, 389; 389, identifier:i; 390, integer:2; 391, attribute; 391, 392; 391, 393; 392, identifier:self; 393, identifier:__m; 394, if_statement; 394, 395; 394, 400; 395, comparison_operator:!=; 395, 396; 395, 399; 396, attribute; 396, 397; 396, 398; 397, identifier:self; 398, identifier:__lambda; 399, integer:0; 400, block; 400, 401; 400, 450; 401, expression_statement; 401, 402; 402, augmented_assignment:+=; 402, 403; 402, 404; 403, identifier:theta_grad; 404, binary_operator:/; 404, 405; 404, 447; 405, binary_operator:*; 405, 406; 405, 444; 406, call; 406, 407; 406, 410; 407, attribute; 407, 408; 407, 409; 408, identifier:np; 409, identifier:concatenate; 410, argument_list; 410, 411; 410, 441; 411, tuple; 411, 412; 411, 429; 412, call; 412, 413; 412, 416; 413, attribute; 413, 414; 413, 415; 414, identifier:np; 415, identifier:zeros; 416, argument_list; 416, 417; 417, tuple; 417, 418; 417, 428; 418, subscript; 418, 419; 418, 427; 419, attribute; 419, 420; 419, 426; 420, subscript; 420, 421; 420, 422; 421, identifier:params; 422, binary_operator:-; 422, 423; 422, 425; 423, unary_operator:-; 423, 424; 424, integer:1; 425, identifier:i; 426, identifier:shape; 427, integer:0; 428, integer:1; 429, subscript; 429, 430; 429, 436; 429, 438; 430, subscript; 430, 431; 430, 432; 431, identifier:params; 432, binary_operator:-; 432, 433; 432, 435; 433, unary_operator:-; 433, 434; 434, integer:1; 435, identifier:i; 436, slice; 436, 437; 437, colon; 438, slice; 438, 439; 438, 440; 439, integer:1; 440, colon; 441, keyword_argument; 441, 442; 441, 443; 442, identifier:axis; 443, integer:1; 444, attribute; 444, 445; 444, 446; 445, identifier:self; 446, identifier:__lambda; 447, attribute; 447, 448; 447, 449; 448, identifier:self; 449, identifier:__m; 450, comment; 451, expression_statement; 451, 452; 452, call; 452, 453; 452, 456; 453, attribute; 453, 454; 453, 455; 454, identifier:reversed_theta_grad; 455, identifier:append; 456, argument_list; 456, 457; 457, identifier:theta_grad; 458, expression_statement; 458, 459; 459, assignment; 459, 460; 459, 461; 460, identifier:theta_grad; 461, call; 461, 462; 461, 465; 462, attribute; 462, 463; 462, 464; 463, identifier:self; 464, identifier:__unroll; 465, argument_list; 465, 466; 466, call; 466, 467; 466, 468; 467, identifier:reversed; 468, argument_list; 468, 469; 469, identifier:reversed_theta_grad; 470, return_statement; 470, 471; 471, identifier:theta_grad
def __cost(self, params, phase, X): """Computes activation, cost function, and derivative.""" params = self.__roll(params) a = np.concatenate((np.ones((X.shape[0], 1)), X), axis=1) # This is a1 calculated_a = [a] # a1 is at index 0, a_n is at index n-1 calculated_z = [0] # There is no z1, z_n is at index n-1 for i, theta in enumerate(params): # calculated_a now contains a1, a2, a3 if there was only one hidden layer (two theta matrices) z = calculated_a[-1] * theta.transpose() # z_n = a_n-1 * Theta_n-1' calculated_z.append(z) # Save the new z_n a = self.sigmoid(z) # a_n = sigmoid(z_n) if i != len(params) - 1: # Don't append extra ones for the output layer a = np.concatenate((np.ones((a.shape[0], 1)), a), axis=1) # Append the extra column of ones for all other layers calculated_a.append(a) # Save the new a if phase == 0: if self.__num_labels > 1: return np.argmax(calculated_a[-1], axis=1) return np.round(calculated_a[-1]) J = np.sum(-np.multiply(self.__y, np.log(calculated_a[-1]))-np.multiply(1-self.__y, np.log(1-calculated_a[-1])))/self.__m; # Calculate cost if self.__lambda != 0: # If we're using regularization... J += np.sum([np.sum(np.power(theta[:,1:], 2)) for theta in params])*self.__lambda/(2.0*self.__m) # ...add it from all theta matrices if phase == 1: return J reversed_d = [] reversed_theta_grad = [] for i in range(len(params)): # For once per theta matrix... if i == 0: # ...if it's the first one... d = calculated_a[-1] - self.__y # ...initialize the error... else: # ...otherwise d_n-1 = d_n * Theta_n-1[missing ones] .* sigmoid(z_n-1) d = np.multiply(reversed_d[-1]*params[-i][:,1:], self.sigmoid_grad(calculated_z[-1-i])) # With i=1/1 hidden layer we're getting Theta2 at index -1, and z2 at index -2 reversed_d.append(d) theta_grad = reversed_d[-1].transpose() * calculated_a[-i-2] / self.__m if self.__lambda != 0: theta_grad += np.concatenate((np.zeros((params[-1-i].shape[0], 1)), params[-1-i][:,1:]), axis=1) * self.__lambda / self.__m# regularization reversed_theta_grad.append(theta_grad) theta_grad = self.__unroll(reversed(reversed_theta_grad)) return theta_grad
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:insert_many; 3, parameters; 3, 4; 3, 5; 4, identifier:self; 5, identifier:it; 6, block; 6, 7; 6, 9; 6, 15; 6, 16; 6, 22; 6, 29; 6, 144; 6, 183; 7, expression_statement; 7, 8; 8, comment; 9, expression_statement; 9, 10; 10, assignment; 10, 11; 10, 12; 11, identifier:unique_indexes; 12, attribute; 12, 13; 12, 14; 13, identifier:self; 14, identifier:_uniqueIndexes; 15, comment; 16, expression_statement; 16, 17; 17, assignment; 17, 18; 17, 19; 18, identifier:NO_SUCH_ATTR; 19, call; 19, 20; 19, 21; 20, identifier:object; 21, argument_list; 22, expression_statement; 22, 23; 23, assignment; 23, 24; 23, 25; 24, identifier:new_objs; 25, call; 25, 26; 25, 27; 26, identifier:list; 27, argument_list; 27, 28; 28, identifier:it; 29, if_statement; 29, 30; 29, 31; 30, identifier:unique_indexes; 31, block; 31, 32; 32, for_statement; 32, 33; 32, 34; 32, 35; 33, identifier:ind; 34, identifier:unique_indexes; 35, block; 35, 36; 35, 42; 35, 59; 35, 95; 35, 113; 36, expression_statement; 36, 37; 37, assignment; 37, 38; 37, 39; 38, identifier:ind_attr; 39, attribute; 39, 40; 39, 41; 40, identifier:ind; 41, identifier:attr; 42, expression_statement; 42, 43; 43, assignment; 43, 44; 43, 45; 44, identifier:new_keys; 45, call; 45, 46; 45, 47; 46, identifier:dict; 47, generator_expression; 47, 48; 47, 56; 48, tuple; 48, 49; 48, 55; 49, call; 49, 50; 49, 51; 50, identifier:getattr; 51, argument_list; 51, 52; 51, 53; 51, 54; 52, identifier:obj; 53, identifier:ind_attr; 54, identifier:NO_SUCH_ATTR; 55, identifier:obj; 56, for_in_clause; 56, 57; 56, 58; 57, identifier:obj; 58, identifier:new_objs; 59, if_statement; 59, 60; 59, 73; 60, boolean_operator:and; 60, 61; 60, 65; 61, not_operator; 61, 62; 62, attribute; 62, 63; 62, 64; 63, identifier:ind; 64, identifier:accept_none; 65, parenthesized_expression; 65, 66; 66, boolean_operator:or; 66, 67; 66, 70; 67, comparison_operator:in; 67, 68; 67, 69; 68, None; 69, identifier:new_keys; 70, comparison_operator:in; 70, 71; 70, 72; 71, identifier:NO_SUCH_ATTR; 72, identifier:new_keys; 73, block; 73, 74; 74, raise_statement; 74, 75; 75, call; 75, 76; 75, 77; 76, identifier:KeyError; 77, argument_list; 77, 78; 77, 81; 78, binary_operator:%; 78, 79; 78, 80; 79, string:"unique key cannot be None or blank for index %s"; 80, identifier:ind_attr; 81, list_comprehension; 81, 82; 81, 83; 81, 86; 82, identifier:ob; 83, for_in_clause; 83, 84; 83, 85; 84, identifier:ob; 85, identifier:new_objs; 86, if_clause; 86, 87; 87, comparison_operator:is; 87, 88; 87, 94; 88, call; 88, 89; 88, 90; 89, identifier:getattr; 90, argument_list; 90, 91; 90, 92; 90, 93; 91, identifier:ob; 92, identifier:ind_attr; 93, identifier:NO_SUCH_ATTR; 94, None; 95, if_statement; 95, 96; 95, 105; 96, comparison_operator:<; 96, 97; 96, 101; 97, call; 97, 98; 97, 99; 98, identifier:len; 99, argument_list; 99, 100; 100, identifier:new_keys; 101, call; 101, 102; 101, 103; 102, identifier:len; 103, argument_list; 103, 104; 104, identifier:new_objs; 105, block; 105, 106; 106, raise_statement; 106, 107; 107, call; 107, 108; 107, 109; 108, identifier:KeyError; 109, argument_list; 109, 110; 110, binary_operator:%; 110, 111; 110, 112; 111, string:"given sequence contains duplicate keys for index %s"; 112, identifier:ind_attr; 113, for_statement; 113, 114; 113, 115; 113, 116; 114, identifier:key; 115, identifier:new_keys; 116, block; 116, 117; 117, if_statement; 117, 118; 117, 121; 118, comparison_operator:in; 118, 119; 118, 120; 119, identifier:key; 120, identifier:ind; 121, block; 121, 122; 121, 128; 122, expression_statement; 122, 123; 123, assignment; 123, 124; 123, 125; 124, identifier:obj; 125, subscript; 125, 126; 125, 127; 126, identifier:new_keys; 127, identifier:key; 128, raise_statement; 128, 129; 129, call; 129, 130; 129, 131; 130, identifier:KeyError; 131, argument_list; 131, 132; 131, 141; 132, binary_operator:%; 132, 133; 132, 134; 133, string:"duplicate unique key value '%s' for index %s"; 134, tuple; 134, 135; 134, 140; 135, call; 135, 136; 135, 137; 136, identifier:getattr; 137, argument_list; 137, 138; 137, 139; 138, identifier:obj; 139, identifier:ind_attr; 140, identifier:ind_attr; 141, subscript; 141, 142; 141, 143; 142, identifier:new_keys; 143, identifier:key; 144, for_statement; 144, 145; 144, 146; 144, 147; 145, identifier:obj; 146, identifier:new_objs; 147, block; 147, 148; 147, 157; 148, expression_statement; 148, 149; 149, call; 149, 150; 149, 155; 150, attribute; 150, 151; 150, 154; 151, attribute; 151, 152; 151, 153; 152, identifier:self; 153, identifier:obs; 154, identifier:append; 155, argument_list; 155, 156; 156, identifier:obj; 157, for_statement; 157, 158; 157, 161; 157, 168; 158, pattern_list; 158, 159; 158, 160; 159, identifier:attr; 160, identifier:ind; 161, call; 161, 162; 161, 167; 162, attribute; 162, 163; 162, 166; 163, attribute; 163, 164; 163, 165; 164, identifier:self; 165, identifier:_indexes; 166, identifier:items; 167, argument_list; 168, block; 168, 169; 168, 177; 169, expression_statement; 169, 170; 170, assignment; 170, 171; 170, 172; 171, identifier:obval; 172, call; 172, 173; 172, 174; 173, identifier:getattr; 174, argument_list; 174, 175; 174, 176; 175, identifier:obj; 176, identifier:attr; 177, expression_statement; 177, 178; 178, assignment; 178, 179; 178, 182; 179, subscript; 179, 180; 179, 181; 180, identifier:ind; 181, identifier:obval; 182, identifier:obj; 183, return_statement; 183, 184; 184, identifier:self
def insert_many(self, it): """Inserts a collection of objects into the table.""" unique_indexes = self._uniqueIndexes # [ind for ind in self._indexes.values() if ind.is_unique] NO_SUCH_ATTR = object() new_objs = list(it) if unique_indexes: for ind in unique_indexes: ind_attr = ind.attr new_keys = dict((getattr(obj, ind_attr, NO_SUCH_ATTR), obj) for obj in new_objs) if not ind.accept_none and (None in new_keys or NO_SUCH_ATTR in new_keys): raise KeyError("unique key cannot be None or blank for index %s" % ind_attr, [ob for ob in new_objs if getattr(ob, ind_attr, NO_SUCH_ATTR) is None]) if len(new_keys) < len(new_objs): raise KeyError("given sequence contains duplicate keys for index %s" % ind_attr) for key in new_keys: if key in ind: obj = new_keys[key] raise KeyError("duplicate unique key value '%s' for index %s" % (getattr(obj, ind_attr), ind_attr), new_keys[key]) for obj in new_objs: self.obs.append(obj) for attr, ind in self._indexes.items(): obval = getattr(obj, attr) ind[obval] = obj return self
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:_query_attr_sort_fn; 3, parameters; 3, 4; 3, 5; 4, identifier:self; 5, identifier:attr_val; 6, block; 6, 7; 6, 9; 6, 15; 7, expression_statement; 7, 8; 8, comment; 9, expression_statement; 9, 10; 10, assignment; 10, 11; 10, 14; 11, pattern_list; 11, 12; 11, 13; 12, identifier:attr; 13, identifier:v; 14, identifier:attr_val; 15, if_statement; 15, 16; 15, 21; 15, 46; 16, comparison_operator:in; 16, 17; 16, 18; 17, identifier:attr; 18, attribute; 18, 19; 18, 20; 19, identifier:self; 20, identifier:_indexes; 21, block; 21, 22; 21, 30; 22, expression_statement; 22, 23; 23, assignment; 23, 24; 23, 25; 24, identifier:idx; 25, subscript; 25, 26; 25, 29; 26, attribute; 26, 27; 26, 28; 27, identifier:self; 28, identifier:_indexes; 29, identifier:attr; 30, if_statement; 30, 31; 30, 34; 30, 42; 31, comparison_operator:in; 31, 32; 31, 33; 32, identifier:v; 33, identifier:idx; 34, block; 34, 35; 35, return_statement; 35, 36; 36, call; 36, 37; 36, 38; 37, identifier:len; 38, argument_list; 38, 39; 39, subscript; 39, 40; 39, 41; 40, identifier:idx; 41, identifier:v; 42, else_clause; 42, 43; 43, block; 43, 44; 44, return_statement; 44, 45; 45, integer:0; 46, else_clause; 46, 47; 47, block; 47, 48; 48, return_statement; 48, 49; 49, float:1e9
def _query_attr_sort_fn(self, attr_val): """Used to order where keys by most selective key first""" attr, v = attr_val if attr in self._indexes: idx = self._indexes[attr] if v in idx: return len(idx[v]) else: return 0 else: return 1e9
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 9; 2, function_name:sort; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:self; 5, identifier:key; 6, default_parameter; 6, 7; 6, 8; 7, identifier:reverse; 8, False; 9, block; 9, 10; 9, 12; 9, 235; 10, expression_statement; 10, 11; 11, comment; 12, if_statement; 12, 13; 12, 21; 12, 214; 13, call; 13, 14; 13, 15; 14, identifier:isinstance; 15, argument_list; 15, 16; 15, 17; 16, identifier:key; 17, tuple; 17, 18; 17, 19; 17, 20; 18, identifier:basestring; 19, identifier:list; 20, identifier:tuple; 21, block; 21, 22; 21, 104; 21, 114; 21, 115; 22, if_statement; 22, 23; 22, 28; 22, 66; 23, call; 23, 24; 23, 25; 24, identifier:isinstance; 25, argument_list; 25, 26; 25, 27; 26, identifier:key; 27, identifier:basestring; 28, block; 28, 29; 28, 46; 29, expression_statement; 29, 30; 30, assignment; 30, 31; 30, 32; 31, identifier:attrdefs; 32, list_comprehension; 32, 33; 32, 38; 33, call; 33, 34; 33, 37; 34, attribute; 34, 35; 34, 36; 35, identifier:s; 36, identifier:strip; 37, argument_list; 38, for_in_clause; 38, 39; 38, 40; 39, identifier:s; 40, call; 40, 41; 40, 44; 41, attribute; 41, 42; 41, 43; 42, identifier:key; 43, identifier:split; 44, argument_list; 44, 45; 45, string:','; 46, expression_statement; 46, 47; 47, assignment; 47, 48; 47, 49; 48, identifier:attr_orders; 49, list_comprehension; 49, 50; 49, 63; 50, subscript; 50, 51; 50, 60; 51, parenthesized_expression; 51, 52; 52, binary_operator:+; 52, 53; 52, 58; 53, call; 53, 54; 53, 57; 54, attribute; 54, 55; 54, 56; 55, identifier:a; 56, identifier:split; 57, argument_list; 58, list:['asc', ]; 58, 59; 59, string:'asc'; 60, slice; 60, 61; 60, 62; 61, colon; 62, integer:2; 63, for_in_clause; 63, 64; 63, 65; 64, identifier:a; 65, identifier:attrdefs; 66, else_clause; 66, 67; 66, 68; 67, comment; 68, block; 68, 69; 69, if_statement; 69, 70; 69, 77; 69, 98; 70, call; 70, 71; 70, 72; 71, identifier:isinstance; 72, argument_list; 72, 73; 72, 76; 73, subscript; 73, 74; 73, 75; 74, identifier:key; 75, integer:0; 76, identifier:basestring; 77, block; 77, 78; 78, expression_statement; 78, 79; 79, assignment; 79, 80; 79, 81; 80, identifier:attr_orders; 81, list_comprehension; 81, 82; 81, 95; 82, subscript; 82, 83; 82, 92; 83, parenthesized_expression; 83, 84; 84, binary_operator:+; 84, 85; 84, 90; 85, call; 85, 86; 85, 89; 86, attribute; 86, 87; 86, 88; 87, identifier:a; 88, identifier:split; 89, argument_list; 90, list:['asc', ]; 90, 91; 91, string:'asc'; 92, slice; 92, 93; 92, 94; 93, colon; 94, integer:2; 95, for_in_clause; 95, 96; 95, 97; 96, identifier:a; 97, identifier:key; 98, else_clause; 98, 99; 99, block; 99, 100; 100, expression_statement; 100, 101; 101, assignment; 101, 102; 101, 103; 102, identifier:attr_orders; 103, identifier:key; 104, expression_statement; 104, 105; 105, assignment; 105, 106; 105, 107; 106, identifier:attrs; 107, list_comprehension; 107, 108; 107, 109; 108, identifier:attr; 109, for_in_clause; 109, 110; 109, 113; 110, pattern_list; 110, 111; 110, 112; 111, identifier:attr; 112, identifier:order; 113, identifier:attr_orders; 114, comment; 115, if_statement; 115, 116; 115, 127; 115, 146; 115, 178; 116, call; 116, 117; 116, 118; 117, identifier:all; 118, generator_expression; 118, 119; 118, 122; 119, comparison_operator:==; 119, 120; 119, 121; 120, identifier:order; 121, string:'asc'; 122, for_in_clause; 122, 123; 122, 126; 123, pattern_list; 123, 124; 123, 125; 124, identifier:attr; 125, identifier:order; 126, identifier:attr_orders; 127, block; 127, 128; 128, expression_statement; 128, 129; 129, call; 129, 130; 129, 135; 130, attribute; 130, 131; 130, 134; 131, attribute; 131, 132; 131, 133; 132, identifier:self; 133, identifier:obs; 134, identifier:sort; 135, argument_list; 135, 136; 135, 143; 136, keyword_argument; 136, 137; 136, 138; 137, identifier:key; 138, call; 138, 139; 138, 140; 139, identifier:attrgetter; 140, argument_list; 140, 141; 141, list_splat; 141, 142; 142, identifier:attrs; 143, keyword_argument; 143, 144; 143, 145; 144, identifier:reverse; 145, identifier:reverse; 146, elif_clause; 146, 147; 146, 158; 147, call; 147, 148; 147, 149; 148, identifier:all; 149, generator_expression; 149, 150; 149, 153; 150, comparison_operator:==; 150, 151; 150, 152; 151, identifier:order; 152, string:'desc'; 153, for_in_clause; 153, 154; 153, 157; 154, pattern_list; 154, 155; 154, 156; 155, identifier:attr; 156, identifier:order; 157, identifier:attr_orders; 158, block; 158, 159; 159, expression_statement; 159, 160; 160, call; 160, 161; 160, 166; 161, attribute; 161, 162; 161, 165; 162, attribute; 162, 163; 162, 164; 163, identifier:self; 164, identifier:obs; 165, identifier:sort; 166, argument_list; 166, 167; 166, 174; 167, keyword_argument; 167, 168; 167, 169; 168, identifier:key; 169, call; 169, 170; 169, 171; 170, identifier:attrgetter; 171, argument_list; 171, 172; 172, list_splat; 172, 173; 173, identifier:attrs; 174, keyword_argument; 174, 175; 174, 176; 175, identifier:reverse; 176, not_operator; 176, 177; 177, identifier:reverse; 178, else_clause; 178, 179; 178, 180; 178, 181; 178, 182; 179, comment; 180, comment; 181, comment; 182, block; 182, 183; 183, expression_statement; 183, 184; 184, call; 184, 185; 184, 186; 185, identifier:do_all; 186, generator_expression; 186, 187; 186, 206; 187, call; 187, 188; 187, 193; 188, attribute; 188, 189; 188, 192; 189, attribute; 189, 190; 189, 191; 190, identifier:self; 191, identifier:obs; 192, identifier:sort; 193, argument_list; 193, 194; 193, 200; 194, keyword_argument; 194, 195; 194, 196; 195, identifier:key; 196, call; 196, 197; 196, 198; 197, identifier:attrgetter; 198, argument_list; 198, 199; 199, identifier:attr; 200, keyword_argument; 200, 201; 200, 202; 201, identifier:reverse; 202, parenthesized_expression; 202, 203; 203, comparison_operator:==; 203, 204; 203, 205; 204, identifier:order; 205, string:"desc"; 206, for_in_clause; 206, 207; 206, 210; 207, pattern_list; 207, 208; 207, 209; 208, identifier:attr; 209, identifier:order; 210, call; 210, 211; 210, 212; 211, identifier:reversed; 212, argument_list; 212, 213; 213, identifier:attr_orders; 214, else_clause; 214, 215; 214, 216; 215, comment; 216, block; 216, 217; 216, 221; 217, expression_statement; 217, 218; 218, assignment; 218, 219; 218, 220; 219, identifier:keyfn; 220, identifier:key; 221, expression_statement; 221, 222; 222, call; 222, 223; 222, 228; 223, attribute; 223, 224; 223, 227; 224, attribute; 224, 225; 224, 226; 225, identifier:self; 226, identifier:obs; 227, identifier:sort; 228, argument_list; 228, 229; 228, 232; 229, keyword_argument; 229, 230; 229, 231; 230, identifier:key; 231, identifier:keyfn; 232, keyword_argument; 232, 233; 232, 234; 233, identifier:reverse; 234, identifier:reverse; 235, return_statement; 235, 236; 236, identifier:self
def sort(self, key, reverse=False): """Sort Table in place, using given fields as sort key. @param key: if this is a string, it is a comma-separated list of field names, optionally followed by 'desc' to indicate descending sort instead of the default ascending sort; if a list or tuple, it is a list or tuple of field names or field names with ' desc' appended; if it is a function, then it is the function to be used as the sort key function @param reverse: (default=False) set to True if results should be in reverse order @type reverse: bool @return: self """ if isinstance(key, (basestring, list, tuple)): if isinstance(key, basestring): attrdefs = [s.strip() for s in key.split(',')] attr_orders = [(a.split()+['asc', ])[:2] for a in attrdefs] else: # attr definitions were already resolved to a sequence by the caller if isinstance(key[0], basestring): attr_orders = [(a.split()+['asc', ])[:2] for a in key] else: attr_orders = key attrs = [attr for attr, order in attr_orders] # special optimization if all orders are ascending or descending if all(order == 'asc' for attr, order in attr_orders): self.obs.sort(key=attrgetter(*attrs), reverse=reverse) elif all(order == 'desc' for attr, order in attr_orders): self.obs.sort(key=attrgetter(*attrs), reverse=not reverse) else: # mix of ascending and descending sorts, have to do succession of sorts # leftmost attr is the most primary sort key, so reverse attr_orders to do # succession of sorts from right to left do_all(self.obs.sort(key=attrgetter(attr), reverse=(order == "desc")) for attr, order in reversed(attr_orders)) else: # sorting given a sort key function keyfn = key self.obs.sort(key=keyfn, reverse=reverse) return self
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 8; 2, function_name:select; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:self; 5, identifier:fields; 6, dictionary_splat_pattern; 6, 7; 7, identifier:exprs; 8, block; 8, 9; 8, 11; 8, 20; 8, 43; 8, 64; 8, 68; 8, 116; 8, 132; 8, 138; 8, 171; 9, expression_statement; 9, 10; 10, comment; 11, expression_statement; 11, 12; 12, assignment; 12, 13; 12, 14; 13, identifier:fields; 14, call; 14, 15; 14, 18; 15, attribute; 15, 16; 15, 17; 16, identifier:self; 17, identifier:_parse_fields_string; 18, argument_list; 18, 19; 19, identifier:fields; 20, function_definition; 20, 21; 20, 22; 20, 24; 21, function_name:_make_string_callable; 22, parameters; 22, 23; 23, identifier:expr; 24, block; 24, 25; 25, if_statement; 25, 26; 25, 31; 25, 39; 26, call; 26, 27; 26, 28; 27, identifier:isinstance; 28, argument_list; 28, 29; 28, 30; 29, identifier:expr; 30, identifier:basestring; 31, block; 31, 32; 32, return_statement; 32, 33; 33, lambda; 33, 34; 33, 36; 34, lambda_parameters; 34, 35; 35, identifier:r; 36, binary_operator:%; 36, 37; 36, 38; 37, identifier:expr; 38, identifier:r; 39, else_clause; 39, 40; 40, block; 40, 41; 41, return_statement; 41, 42; 42, identifier:expr; 43, expression_statement; 43, 44; 44, assignment; 44, 45; 44, 46; 45, identifier:exprs; 46, call; 46, 47; 46, 48; 47, identifier:dict; 48, generator_expression; 48, 49; 48, 55; 49, tuple; 49, 50; 49, 51; 50, identifier:k; 51, call; 51, 52; 51, 53; 52, identifier:_make_string_callable; 53, argument_list; 53, 54; 54, identifier:v; 55, for_in_clause; 55, 56; 55, 59; 56, pattern_list; 56, 57; 56, 58; 57, identifier:k; 58, identifier:v; 59, call; 59, 60; 59, 63; 60, attribute; 60, 61; 60, 62; 61, identifier:exprs; 62, identifier:items; 63, argument_list; 64, expression_statement; 64, 65; 65, assignment; 65, 66; 65, 67; 66, identifier:raw_tuples; 67, list:[]; 68, for_statement; 68, 69; 68, 70; 68, 73; 69, identifier:ob; 70, attribute; 70, 71; 70, 72; 71, identifier:self; 72, identifier:obs; 73, block; 73, 74; 73, 89; 73, 109; 74, expression_statement; 74, 75; 75, assignment; 75, 76; 75, 77; 76, identifier:attrvalues; 77, call; 77, 78; 77, 79; 78, identifier:tuple; 79, generator_expression; 79, 80; 79, 86; 80, call; 80, 81; 80, 82; 81, identifier:getattr; 82, argument_list; 82, 83; 82, 84; 82, 85; 83, identifier:ob; 84, identifier:fieldname; 85, None; 86, for_in_clause; 86, 87; 86, 88; 87, identifier:fieldname; 88, identifier:fields; 89, if_statement; 89, 90; 89, 91; 90, identifier:exprs; 91, block; 91, 92; 92, expression_statement; 92, 93; 93, augmented_assignment:+=; 93, 94; 93, 95; 94, identifier:attrvalues; 95, call; 95, 96; 95, 97; 96, identifier:tuple; 97, generator_expression; 97, 98; 97, 102; 98, call; 98, 99; 98, 100; 99, identifier:expr; 100, argument_list; 100, 101; 101, identifier:ob; 102, for_in_clause; 102, 103; 102, 104; 103, identifier:expr; 104, call; 104, 105; 104, 108; 105, attribute; 105, 106; 105, 107; 106, identifier:exprs; 107, identifier:values; 108, argument_list; 109, expression_statement; 109, 110; 110, call; 110, 111; 110, 114; 111, attribute; 111, 112; 111, 113; 112, identifier:raw_tuples; 113, identifier:append; 114, argument_list; 114, 115; 115, identifier:attrvalues; 116, expression_statement; 116, 117; 117, assignment; 117, 118; 117, 119; 118, identifier:all_names; 119, binary_operator:+; 119, 120; 119, 124; 120, call; 120, 121; 120, 122; 121, identifier:tuple; 122, argument_list; 122, 123; 123, identifier:fields; 124, call; 124, 125; 124, 126; 125, identifier:tuple; 126, argument_list; 126, 127; 127, call; 127, 128; 127, 131; 128, attribute; 128, 129; 128, 130; 129, identifier:exprs; 130, identifier:keys; 131, argument_list; 132, expression_statement; 132, 133; 133, assignment; 133, 134; 133, 135; 134, identifier:ret; 135, call; 135, 136; 135, 137; 136, identifier:Table; 137, argument_list; 138, expression_statement; 138, 139; 139, call; 139, 140; 139, 145; 140, attribute; 140, 141; 140, 144; 141, attribute; 141, 142; 141, 143; 142, identifier:ret; 143, identifier:_indexes; 144, identifier:update; 145, argument_list; 145, 146; 146, call; 146, 147; 146, 148; 147, identifier:dict; 148, generator_expression; 148, 149; 148, 156; 148, 167; 149, tuple; 149, 150; 149, 151; 150, identifier:k; 151, call; 151, 152; 151, 155; 152, attribute; 152, 153; 152, 154; 153, identifier:v; 154, identifier:copy_template; 155, argument_list; 156, for_in_clause; 156, 157; 156, 160; 157, pattern_list; 157, 158; 157, 159; 158, identifier:k; 159, identifier:v; 160, call; 160, 161; 160, 166; 161, attribute; 161, 162; 161, 165; 162, attribute; 162, 163; 162, 164; 163, identifier:self; 164, identifier:_indexes; 165, identifier:items; 166, argument_list; 167, if_clause; 167, 168; 168, comparison_operator:in; 168, 169; 168, 170; 169, identifier:k; 170, identifier:all_names; 171, return_statement; 171, 172; 172, call; 172, 173; 172, 178; 173, attribute; 173, 174; 173, 177; 174, call; 174, 175; 174, 176; 175, identifier:ret; 176, argument_list; 177, identifier:insert_many; 178, generator_expression; 178, 179; 178, 191; 179, call; 179, 180; 179, 181; 180, identifier:DataObject; 181, argument_list; 181, 182; 182, dictionary_splat; 182, 183; 183, call; 183, 184; 183, 185; 184, identifier:dict; 185, argument_list; 185, 186; 186, call; 186, 187; 186, 188; 187, identifier:zip; 188, argument_list; 188, 189; 188, 190; 189, identifier:all_names; 190, identifier:outtuple; 191, for_in_clause; 191, 192; 191, 193; 192, identifier:outtuple; 193, identifier:raw_tuples
def select(self, fields, **exprs): """ Create a new table containing a subset of attributes, with optionally newly-added fields computed from each rec in the original table. @param fields: list of strings, or single space-delimited string, listing attribute name to be included in the output @type fields: list, or space-delimited string @param exprs: one or more named callable arguments, to compute additional fields using the given function @type exprs: C{name=callable}, callable takes the record as an argument, and returns the new attribute value If a string is passed as a callable, this string will be used using string formatting, given the record as a source of interpolation values. For instance, C{fullName = '%(lastName)s, %(firstName)s'} """ fields = self._parse_fields_string(fields) def _make_string_callable(expr): if isinstance(expr, basestring): return lambda r: expr % r else: return expr exprs = dict((k, _make_string_callable(v)) for k, v in exprs.items()) raw_tuples = [] for ob in self.obs: attrvalues = tuple(getattr(ob, fieldname, None) for fieldname in fields) if exprs: attrvalues += tuple(expr(ob) for expr in exprs.values()) raw_tuples.append(attrvalues) all_names = tuple(fields) + tuple(exprs.keys()) ret = Table() ret._indexes.update(dict((k, v.copy_template()) for k, v in self._indexes.items() if k in all_names)) return ret().insert_many(DataObject(**dict(zip(all_names, outtuple))) for outtuple in raw_tuples)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 17; 2, function_name:csv_import; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 3, 12; 3, 15; 4, identifier:self; 5, identifier:csv_source; 6, default_parameter; 6, 7; 6, 8; 7, identifier:encoding; 8, string:'utf-8'; 9, default_parameter; 9, 10; 9, 11; 10, identifier:transforms; 11, None; 12, default_parameter; 12, 13; 12, 14; 13, identifier:row_class; 14, identifier:DataObject; 15, dictionary_splat_pattern; 15, 16; 16, identifier:kwargs; 17, block; 17, 18; 17, 20; 17, 46; 17, 60; 18, expression_statement; 18, 19; 19, comment; 20, expression_statement; 20, 21; 21, assignment; 21, 22; 21, 23; 22, identifier:reader_args; 23, call; 23, 24; 23, 25; 24, identifier:dict; 25, generator_expression; 25, 26; 25, 29; 25, 38; 26, tuple; 26, 27; 26, 28; 27, identifier:k; 28, identifier:v; 29, for_in_clause; 29, 30; 29, 33; 30, pattern_list; 30, 31; 30, 32; 31, identifier:k; 32, identifier:v; 33, call; 33, 34; 33, 37; 34, attribute; 34, 35; 34, 36; 35, identifier:kwargs; 36, identifier:items; 37, argument_list; 38, if_clause; 38, 39; 39, comparison_operator:not; 39, 40; 39, 41; 40, identifier:k; 41, list:['encoding', 'csv_source', 'transforms', 'row_class']; 41, 42; 41, 43; 41, 44; 41, 45; 42, string:'encoding'; 43, string:'csv_source'; 44, string:'transforms'; 45, string:'row_class'; 46, expression_statement; 46, 47; 47, assignment; 47, 48; 47, 49; 48, identifier:reader; 49, lambda; 49, 50; 49, 52; 50, lambda_parameters; 50, 51; 51, identifier:src; 52, call; 52, 53; 52, 56; 53, attribute; 53, 54; 53, 55; 54, identifier:csv; 55, identifier:DictReader; 56, argument_list; 56, 57; 56, 58; 57, identifier:src; 58, dictionary_splat; 58, 59; 59, identifier:reader_args; 60, return_statement; 60, 61; 61, call; 61, 62; 61, 65; 62, attribute; 62, 63; 62, 64; 63, identifier:self; 64, identifier:_import; 65, argument_list; 65, 66; 65, 67; 65, 68; 65, 69; 65, 72; 66, identifier:csv_source; 67, identifier:encoding; 68, identifier:transforms; 69, keyword_argument; 69, 70; 69, 71; 70, identifier:reader; 71, identifier:reader; 72, keyword_argument; 72, 73; 72, 74; 73, identifier:row_class; 74, identifier:row_class
def csv_import(self, csv_source, encoding='utf-8', transforms=None, row_class=DataObject, **kwargs): """Imports the contents of a CSV-formatted file into this table. @param csv_source: CSV file - if a string is given, the file with that name will be opened, read, and closed; if a file object is given, then that object will be read as-is, and left for the caller to be closed. @type csv_source: string or file @param encoding: encoding to be used for reading source text if C{csv_source} is passed as a string filename @type encoding: string (default='UTF-8') @param transforms: dict of functions by attribute name; if given, each attribute will be transformed using the corresponding transform; if there is no matching transform, the attribute will be read as a string (default); the transform function can also be defined as a (function, default-value) tuple; if there is an Exception raised by the transform function, then the attribute will be set to the given default value @type transforms: dict (optional) @param kwargs: additional constructor arguments for csv C{DictReader} objects, such as C{delimiter} or C{fieldnames}; these are passed directly through to the csv C{DictReader} constructor @type kwargs: named arguments (optional) """ reader_args = dict((k, v) for k, v in kwargs.items() if k not in ['encoding', 'csv_source', 'transforms', 'row_class']) reader = lambda src: csv.DictReader(src, **reader_args) return self._import(csv_source, encoding, transforms, reader=reader, row_class=row_class)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 12; 2, function_name:csv_export; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 4, identifier:self; 5, identifier:csv_dest; 6, default_parameter; 6, 7; 6, 8; 7, identifier:fieldnames; 8, None; 9, default_parameter; 9, 10; 9, 11; 10, identifier:encoding; 11, string:"UTF-8"; 12, block; 12, 13; 12, 15; 12, 19; 12, 57; 13, expression_statement; 13, 14; 14, comment; 15, expression_statement; 15, 16; 16, assignment; 16, 17; 16, 18; 17, identifier:close_on_exit; 18, False; 19, if_statement; 19, 20; 19, 25; 20, call; 20, 21; 20, 22; 21, identifier:isinstance; 22, argument_list; 22, 23; 22, 24; 23, identifier:csv_dest; 24, identifier:basestring; 25, block; 25, 26; 25, 53; 26, if_statement; 26, 27; 26, 28; 26, 43; 27, identifier:PY_3; 28, block; 28, 29; 29, expression_statement; 29, 30; 30, assignment; 30, 31; 30, 32; 31, identifier:csv_dest; 32, call; 32, 33; 32, 34; 33, identifier:open; 34, argument_list; 34, 35; 34, 36; 34, 37; 34, 40; 35, identifier:csv_dest; 36, string:'w'; 37, keyword_argument; 37, 38; 37, 39; 38, identifier:newline; 39, string:''; 40, keyword_argument; 40, 41; 40, 42; 41, identifier:encoding; 42, identifier:encoding; 43, else_clause; 43, 44; 44, block; 44, 45; 45, expression_statement; 45, 46; 46, assignment; 46, 47; 46, 48; 47, identifier:csv_dest; 48, call; 48, 49; 48, 50; 49, identifier:open; 50, argument_list; 50, 51; 50, 52; 51, identifier:csv_dest; 52, string:'wb'; 53, expression_statement; 53, 54; 54, assignment; 54, 55; 54, 56; 55, identifier:close_on_exit; 56, True; 57, try_statement; 57, 58; 57, 189; 58, block; 58, 59; 58, 78; 58, 93; 58, 107; 58, 123; 59, if_statement; 59, 60; 59, 63; 60, comparison_operator:is; 60, 61; 60, 62; 61, identifier:fieldnames; 62, None; 63, block; 63, 64; 64, expression_statement; 64, 65; 65, assignment; 65, 66; 65, 67; 66, identifier:fieldnames; 67, call; 67, 68; 67, 69; 68, identifier:list; 69, argument_list; 69, 70; 70, call; 70, 71; 70, 72; 71, identifier:_object_attrnames; 72, argument_list; 72, 73; 73, subscript; 73, 74; 73, 77; 74, attribute; 74, 75; 74, 76; 75, identifier:self; 76, identifier:obs; 77, integer:0; 78, if_statement; 78, 79; 78, 84; 79, call; 79, 80; 79, 81; 80, identifier:isinstance; 81, argument_list; 81, 82; 81, 83; 82, identifier:fieldnames; 83, identifier:basestring; 84, block; 84, 85; 85, expression_statement; 85, 86; 86, assignment; 86, 87; 86, 88; 87, identifier:fieldnames; 88, call; 88, 89; 88, 92; 89, attribute; 89, 90; 89, 91; 90, identifier:fieldnames; 91, identifier:split; 92, argument_list; 93, expression_statement; 93, 94; 94, call; 94, 95; 94, 98; 95, attribute; 95, 96; 95, 97; 96, identifier:csv_dest; 97, identifier:write; 98, argument_list; 98, 99; 99, binary_operator:+; 99, 100; 99, 106; 100, call; 100, 101; 100, 104; 101, attribute; 101, 102; 101, 103; 102, string:','; 103, identifier:join; 104, argument_list; 104, 105; 105, identifier:fieldnames; 106, identifier:NL; 107, expression_statement; 107, 108; 108, assignment; 108, 109; 108, 110; 109, identifier:csvout; 110, call; 110, 111; 110, 114; 111, attribute; 111, 112; 111, 113; 112, identifier:csv; 113, identifier:DictWriter; 114, argument_list; 114, 115; 114, 116; 114, 117; 114, 120; 115, identifier:csv_dest; 116, identifier:fieldnames; 117, keyword_argument; 117, 118; 117, 119; 118, identifier:extrasaction; 119, string:'ignore'; 120, keyword_argument; 120, 121; 120, 122; 121, identifier:lineterminator; 122, identifier:NL; 123, if_statement; 123, 124; 123, 133; 123, 148; 124, call; 124, 125; 124, 126; 125, identifier:hasattr; 126, argument_list; 126, 127; 126, 132; 127, subscript; 127, 128; 127, 131; 128, attribute; 128, 129; 128, 130; 129, identifier:self; 130, identifier:obs; 131, integer:0; 132, string:"__dict__"; 133, block; 133, 134; 134, expression_statement; 134, 135; 135, call; 135, 136; 135, 139; 136, attribute; 136, 137; 136, 138; 137, identifier:csvout; 138, identifier:writerows; 139, generator_expression; 139, 140; 139, 143; 140, attribute; 140, 141; 140, 142; 141, identifier:o; 142, identifier:__dict__; 143, for_in_clause; 143, 144; 143, 145; 144, identifier:o; 145, attribute; 145, 146; 145, 147; 146, identifier:self; 147, identifier:obs; 148, else_clause; 148, 149; 149, block; 149, 150; 150, expression_statement; 150, 151; 151, call; 151, 152; 151, 153; 152, identifier:do_all; 153, generator_expression; 153, 154; 153, 184; 154, call; 154, 155; 154, 158; 155, attribute; 155, 156; 155, 157; 156, identifier:csvout; 157, identifier:writerow; 158, argument_list; 158, 159; 159, call; 159, 160; 159, 161; 160, identifier:ODict; 161, argument_list; 161, 162; 162, call; 162, 163; 162, 164; 163, identifier:starmap; 164, argument_list; 164, 165; 164, 176; 165, lambda; 165, 166; 165, 169; 166, lambda_parameters; 166, 167; 166, 168; 167, identifier:obj; 168, identifier:fld; 169, tuple; 169, 170; 169, 171; 170, identifier:fld; 171, call; 171, 172; 171, 173; 172, identifier:getattr; 173, argument_list; 173, 174; 173, 175; 174, identifier:obj; 175, identifier:fld; 176, call; 176, 177; 176, 178; 177, identifier:zip; 178, argument_list; 178, 179; 178, 183; 179, call; 179, 180; 179, 181; 180, identifier:repeat; 181, argument_list; 181, 182; 182, identifier:o; 183, identifier:fieldnames; 184, for_in_clause; 184, 185; 184, 186; 185, identifier:o; 186, attribute; 186, 187; 186, 188; 187, identifier:self; 188, identifier:obs; 189, finally_clause; 189, 190; 190, block; 190, 191; 191, if_statement; 191, 192; 191, 193; 192, identifier:close_on_exit; 193, block; 193, 194; 194, expression_statement; 194, 195; 195, call; 195, 196; 195, 199; 196, attribute; 196, 197; 196, 198; 197, identifier:csv_dest; 198, identifier:close; 199, argument_list
def csv_export(self, csv_dest, fieldnames=None, encoding="UTF-8"): """Exports the contents of the table to a CSV-formatted file. @param csv_dest: CSV file - if a string is given, the file with that name will be opened, written, and closed; if a file object is given, then that object will be written as-is, and left for the caller to be closed. @type csv_dest: string or file @param fieldnames: attribute names to be exported; can be given as a single string with space-delimited names, or as a list of attribute names @type fieldnames: list of strings @param encoding: string (default="UTF-8"); if csv_dest is provided as a string representing an output filename, an encoding argument can be provided (Python 3 only) @type encoding: string """ close_on_exit = False if isinstance(csv_dest, basestring): if PY_3: csv_dest = open(csv_dest, 'w', newline='', encoding=encoding) else: csv_dest = open(csv_dest, 'wb') close_on_exit = True try: if fieldnames is None: fieldnames = list(_object_attrnames(self.obs[0])) if isinstance(fieldnames, basestring): fieldnames = fieldnames.split() csv_dest.write(','.join(fieldnames) + NL) csvout = csv.DictWriter(csv_dest, fieldnames, extrasaction='ignore', lineterminator=NL) if hasattr(self.obs[0], "__dict__"): csvout.writerows(o.__dict__ for o in self.obs) else: do_all(csvout.writerow(ODict(starmap(lambda obj, fld: (fld, getattr(obj, fld)), zip(repeat(o), fieldnames)))) for o in self.obs) finally: if close_on_exit: csv_dest.close()
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 15; 2, function_name:json_import; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 3, 12; 4, identifier:self; 5, identifier:source; 6, default_parameter; 6, 7; 6, 8; 7, identifier:encoding; 8, string:"UTF-8"; 9, default_parameter; 9, 10; 9, 11; 10, identifier:transforms; 11, None; 12, default_parameter; 12, 13; 12, 14; 13, identifier:row_class; 14, identifier:DataObject; 15, block; 15, 16; 15, 18; 15, 79; 16, expression_statement; 16, 17; 17, comment; 18, class_definition; 18, 19; 18, 20; 18, 22; 19, identifier:_JsonFileReader; 20, argument_list; 20, 21; 21, identifier:object; 22, block; 22, 23; 22, 35; 23, function_definition; 23, 24; 23, 25; 23, 28; 24, function_name:__init__; 25, parameters; 25, 26; 25, 27; 26, identifier:self; 27, identifier:src; 28, block; 28, 29; 29, expression_statement; 29, 30; 30, assignment; 30, 31; 30, 34; 31, attribute; 31, 32; 31, 33; 32, identifier:self; 33, identifier:source; 34, identifier:src; 35, function_definition; 35, 36; 35, 37; 35, 39; 36, function_name:__iter__; 37, parameters; 37, 38; 38, identifier:self; 39, block; 39, 40; 39, 44; 40, expression_statement; 40, 41; 41, assignment; 41, 42; 41, 43; 42, identifier:current; 43, string:''; 44, for_statement; 44, 45; 44, 46; 44, 49; 45, identifier:line; 46, attribute; 46, 47; 46, 48; 47, identifier:self; 48, identifier:source; 49, block; 49, 50; 49, 57; 49, 61; 50, if_statement; 50, 51; 50, 52; 51, identifier:current; 52, block; 52, 53; 53, expression_statement; 53, 54; 54, augmented_assignment:+=; 54, 55; 54, 56; 55, identifier:current; 56, string:' '; 57, expression_statement; 57, 58; 58, augmented_assignment:+=; 58, 59; 58, 60; 59, identifier:current; 60, identifier:line; 61, try_statement; 61, 62; 61, 75; 62, block; 62, 63; 62, 71; 63, expression_statement; 63, 64; 64, yield; 64, 65; 65, call; 65, 66; 65, 69; 66, attribute; 66, 67; 66, 68; 67, identifier:json; 68, identifier:loads; 69, argument_list; 69, 70; 70, identifier:current; 71, expression_statement; 71, 72; 72, assignment; 72, 73; 72, 74; 73, identifier:current; 74, string:''; 75, except_clause; 75, 76; 75, 77; 76, identifier:Exception; 77, block; 77, 78; 78, pass_statement; 79, return_statement; 79, 80; 80, call; 80, 81; 80, 84; 81, attribute; 81, 82; 81, 83; 82, identifier:self; 83, identifier:_import; 84, argument_list; 84, 85; 84, 86; 84, 87; 84, 90; 84, 93; 85, identifier:source; 86, identifier:encoding; 87, keyword_argument; 87, 88; 87, 89; 88, identifier:transforms; 89, identifier:transforms; 90, keyword_argument; 90, 91; 90, 92; 91, identifier:reader; 92, identifier:_JsonFileReader; 93, keyword_argument; 93, 94; 93, 95; 94, identifier:row_class; 95, identifier:row_class
def json_import(self, source, encoding="UTF-8", transforms=None, row_class=DataObject): """Imports the contents of a JSON data file into this table. @param source: JSON data file - if a string is given, the file with that name will be opened, read, and closed; if a file object is given, then that object will be read as-is, and left for the caller to be closed. @type source: string or file @param transforms: dict of functions by attribute name; if given, each attribute will be transformed using the corresponding transform; if there is no matching transform, the attribute will be read as a string (default); the transform function can also be defined as a (function, default-value) tuple; if there is an Exception raised by the transform function, then the attribute will be set to the given default value @type transforms: dict (optional) """ class _JsonFileReader(object): def __init__(self, src): self.source = src def __iter__(self): current = '' for line in self.source: if current: current += ' ' current += line try: yield json.loads(current) current = '' except Exception: pass return self._import(source, encoding, transforms=transforms, reader=_JsonFileReader, row_class=row_class)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 12; 2, function_name:json_export; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 4, identifier:self; 5, identifier:dest; 6, default_parameter; 6, 7; 6, 8; 7, identifier:fieldnames; 8, None; 9, default_parameter; 9, 10; 9, 11; 10, identifier:encoding; 11, string:"UTF-8"; 12, block; 12, 13; 12, 15; 12, 19; 12, 54; 13, expression_statement; 13, 14; 14, comment; 15, expression_statement; 15, 16; 16, assignment; 16, 17; 16, 18; 17, identifier:close_on_exit; 18, False; 19, if_statement; 19, 20; 19, 25; 20, call; 20, 21; 20, 22; 21, identifier:isinstance; 22, argument_list; 22, 23; 22, 24; 23, identifier:dest; 24, identifier:basestring; 25, block; 25, 26; 25, 50; 26, if_statement; 26, 27; 26, 28; 26, 40; 27, identifier:PY_3; 28, block; 28, 29; 29, expression_statement; 29, 30; 30, assignment; 30, 31; 30, 32; 31, identifier:dest; 32, call; 32, 33; 32, 34; 33, identifier:open; 34, argument_list; 34, 35; 34, 36; 34, 37; 35, identifier:dest; 36, string:'w'; 37, keyword_argument; 37, 38; 37, 39; 38, identifier:encoding; 39, identifier:encoding; 40, else_clause; 40, 41; 41, block; 41, 42; 42, expression_statement; 42, 43; 43, assignment; 43, 44; 43, 45; 44, identifier:dest; 45, call; 45, 46; 45, 47; 46, identifier:open; 47, argument_list; 47, 48; 47, 49; 48, identifier:dest; 49, string:'w'; 50, expression_statement; 50, 51; 51, assignment; 51, 52; 51, 53; 52, identifier:close_on_exit; 53, True; 54, try_statement; 54, 55; 54, 132; 55, block; 55, 56; 55, 71; 56, if_statement; 56, 57; 56, 62; 57, call; 57, 58; 57, 59; 58, identifier:isinstance; 59, argument_list; 59, 60; 59, 61; 60, identifier:fieldnames; 61, identifier:basestring; 62, block; 62, 63; 63, expression_statement; 63, 64; 64, assignment; 64, 65; 64, 66; 65, identifier:fieldnames; 66, call; 66, 67; 66, 70; 67, attribute; 67, 68; 67, 69; 68, identifier:fieldnames; 69, identifier:split; 70, argument_list; 71, if_statement; 71, 72; 71, 75; 71, 96; 72, comparison_operator:is; 72, 73; 72, 74; 73, identifier:fieldnames; 74, None; 75, block; 75, 76; 76, expression_statement; 76, 77; 77, call; 77, 78; 77, 79; 78, identifier:do_all; 79, generator_expression; 79, 80; 79, 91; 80, call; 80, 81; 80, 84; 81, attribute; 81, 82; 81, 83; 82, identifier:dest; 83, identifier:write; 84, argument_list; 84, 85; 85, binary_operator:+; 85, 86; 85, 90; 86, call; 86, 87; 86, 88; 87, identifier:_to_json; 88, argument_list; 88, 89; 89, identifier:o; 90, string:'\n'; 91, for_in_clause; 91, 92; 91, 93; 92, identifier:o; 93, attribute; 93, 94; 93, 95; 94, identifier:self; 95, identifier:obs; 96, else_clause; 96, 97; 97, block; 97, 98; 98, expression_statement; 98, 99; 99, call; 99, 100; 99, 101; 100, identifier:do_all; 101, generator_expression; 101, 102; 101, 127; 102, call; 102, 103; 102, 106; 103, attribute; 103, 104; 103, 105; 104, identifier:dest; 105, identifier:write; 106, argument_list; 106, 107; 107, binary_operator:+; 107, 108; 107, 126; 108, call; 108, 109; 108, 112; 109, attribute; 109, 110; 109, 111; 110, identifier:json; 111, identifier:dumps; 112, argument_list; 112, 113; 113, call; 113, 114; 113, 115; 114, identifier:ODict; 115, generator_expression; 115, 116; 115, 123; 116, tuple; 116, 117; 116, 118; 117, identifier:f; 118, call; 118, 119; 118, 120; 119, identifier:getattr; 120, argument_list; 120, 121; 120, 122; 121, identifier:o; 122, identifier:f; 123, for_in_clause; 123, 124; 123, 125; 124, identifier:f; 125, identifier:fieldnames; 126, string:'\n'; 127, for_in_clause; 127, 128; 127, 129; 128, identifier:o; 129, attribute; 129, 130; 129, 131; 130, identifier:self; 131, identifier:obs; 132, finally_clause; 132, 133; 133, block; 133, 134; 134, if_statement; 134, 135; 134, 136; 135, identifier:close_on_exit; 136, block; 136, 137; 137, expression_statement; 137, 138; 138, call; 138, 139; 138, 142; 139, attribute; 139, 140; 139, 141; 140, identifier:dest; 141, identifier:close; 142, argument_list
def json_export(self, dest, fieldnames=None, encoding="UTF-8"): """Exports the contents of the table to a JSON-formatted file. @param dest: output file - if a string is given, the file with that name will be opened, written, and closed; if a file object is given, then that object will be written as-is, and left for the caller to be closed. @type dest: string or file @param fieldnames: attribute names to be exported; can be given as a single string with space-delimited names, or as a list of attribute names @type fieldnames: list of strings @param encoding: string (default="UTF-8"); if csv_dest is provided as a string representing an output filename, an encoding argument can be provided (Python 3 only) @type encoding: string """ close_on_exit = False if isinstance(dest, basestring): if PY_3: dest = open(dest, 'w', encoding=encoding) else: dest = open(dest, 'w') close_on_exit = True try: if isinstance(fieldnames, basestring): fieldnames = fieldnames.split() if fieldnames is None: do_all(dest.write(_to_json(o)+'\n') for o in self.obs) else: do_all(dest.write(json.dumps(ODict((f, getattr(o, f)) for f in fieldnames))+'\n') for o in self.obs) finally: if close_on_exit: dest.close()
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 8; 2, function_name:groupby; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:self; 5, identifier:keyexpr; 6, dictionary_splat_pattern; 6, 7; 7, identifier:outexprs; 8, block; 8, 9; 8, 11; 8, 70; 8, 77; 8, 97; 8, 103; 8, 125; 8, 182; 9, expression_statement; 9, 10; 10, comment; 11, if_statement; 11, 12; 11, 17; 11, 43; 11, 63; 12, call; 12, 13; 12, 14; 13, identifier:isinstance; 14, argument_list; 14, 15; 14, 16; 15, identifier:keyexpr; 16, identifier:basestring; 17, block; 17, 18; 17, 26; 18, expression_statement; 18, 19; 19, assignment; 19, 20; 19, 21; 20, identifier:keyattrs; 21, call; 21, 22; 21, 25; 22, attribute; 22, 23; 22, 24; 23, identifier:keyexpr; 24, identifier:split; 25, argument_list; 26, expression_statement; 26, 27; 27, assignment; 27, 28; 27, 29; 28, identifier:keyfn; 29, lambda; 29, 30; 29, 32; 30, lambda_parameters; 30, 31; 31, identifier:o; 32, call; 32, 33; 32, 34; 33, identifier:tuple; 34, generator_expression; 34, 35; 34, 40; 35, call; 35, 36; 35, 37; 36, identifier:getattr; 37, argument_list; 37, 38; 37, 39; 38, identifier:o; 39, identifier:k; 40, for_in_clause; 40, 41; 40, 42; 41, identifier:k; 42, identifier:keyattrs; 43, elif_clause; 43, 44; 43, 49; 44, call; 44, 45; 44, 46; 45, identifier:isinstance; 46, argument_list; 46, 47; 46, 48; 47, identifier:keyexpr; 48, identifier:tuple; 49, block; 49, 50; 49, 57; 50, expression_statement; 50, 51; 51, assignment; 51, 52; 51, 53; 52, identifier:keyattrs; 53, tuple; 53, 54; 54, subscript; 54, 55; 54, 56; 55, identifier:keyexpr; 56, integer:0; 57, expression_statement; 57, 58; 58, assignment; 58, 59; 58, 60; 59, identifier:keyfn; 60, subscript; 60, 61; 60, 62; 61, identifier:keyexpr; 62, integer:1; 63, else_clause; 63, 64; 64, block; 64, 65; 65, raise_statement; 65, 66; 66, call; 66, 67; 66, 68; 67, identifier:TypeError; 68, argument_list; 68, 69; 69, string:"keyexpr must be string or tuple"; 70, expression_statement; 70, 71; 71, assignment; 71, 72; 71, 73; 72, identifier:groupedobs; 73, call; 73, 74; 73, 75; 74, identifier:defaultdict; 75, argument_list; 75, 76; 76, identifier:list; 77, expression_statement; 77, 78; 78, call; 78, 79; 78, 80; 79, identifier:do_all; 80, generator_expression; 80, 81; 80, 92; 81, call; 81, 82; 81, 90; 82, attribute; 82, 83; 82, 89; 83, subscript; 83, 84; 83, 85; 84, identifier:groupedobs; 85, call; 85, 86; 85, 87; 86, identifier:keyfn; 87, argument_list; 87, 88; 88, identifier:ob; 89, identifier:append; 90, argument_list; 90, 91; 91, identifier:ob; 92, for_in_clause; 92, 93; 92, 94; 93, identifier:ob; 94, attribute; 94, 95; 94, 96; 95, identifier:self; 96, identifier:obs; 97, expression_statement; 97, 98; 98, assignment; 98, 99; 98, 100; 99, identifier:tbl; 100, call; 100, 101; 100, 102; 101, identifier:Table; 102, argument_list; 103, expression_statement; 103, 104; 104, call; 104, 105; 104, 106; 105, identifier:do_all; 106, generator_expression; 106, 107; 106, 122; 107, call; 107, 108; 107, 111; 108, attribute; 108, 109; 108, 110; 109, identifier:tbl; 110, identifier:create_index; 111, argument_list; 111, 112; 111, 113; 112, identifier:k; 113, keyword_argument; 113, 114; 113, 115; 114, identifier:unique; 115, parenthesized_expression; 115, 116; 116, comparison_operator:==; 116, 117; 116, 121; 117, call; 117, 118; 117, 119; 118, identifier:len; 119, argument_list; 119, 120; 120, identifier:keyattrs; 121, integer:1; 122, for_in_clause; 122, 123; 122, 124; 123, identifier:k; 124, identifier:keyattrs; 125, for_statement; 125, 126; 125, 129; 125, 137; 126, pattern_list; 126, 127; 126, 128; 127, identifier:key; 128, identifier:recs; 129, call; 129, 130; 129, 131; 130, identifier:sorted; 131, argument_list; 131, 132; 132, call; 132, 133; 132, 136; 133, attribute; 133, 134; 133, 135; 134, identifier:groupedobs; 135, identifier:items; 136, argument_list; 137, block; 137, 138; 137, 153; 137, 175; 138, expression_statement; 138, 139; 139, assignment; 139, 140; 139, 141; 140, identifier:groupobj; 141, call; 141, 142; 141, 143; 142, identifier:DataObject; 143, argument_list; 143, 144; 144, dictionary_splat; 144, 145; 145, call; 145, 146; 145, 147; 146, identifier:dict; 147, argument_list; 147, 148; 148, call; 148, 149; 148, 150; 149, identifier:zip; 150, argument_list; 150, 151; 150, 152; 151, identifier:keyattrs; 152, identifier:key; 153, expression_statement; 153, 154; 154, call; 154, 155; 154, 156; 155, identifier:do_all; 156, generator_expression; 156, 157; 156, 166; 157, call; 157, 158; 157, 159; 158, identifier:setattr; 159, argument_list; 159, 160; 159, 161; 159, 162; 160, identifier:groupobj; 161, identifier:subkey; 162, call; 162, 163; 162, 164; 163, identifier:expr; 164, argument_list; 164, 165; 165, identifier:recs; 166, for_in_clause; 166, 167; 166, 170; 167, pattern_list; 167, 168; 167, 169; 168, identifier:subkey; 169, identifier:expr; 170, call; 170, 171; 170, 174; 171, attribute; 171, 172; 171, 173; 172, identifier:outexprs; 173, identifier:items; 174, argument_list; 175, expression_statement; 175, 176; 176, call; 176, 177; 176, 180; 177, attribute; 177, 178; 177, 179; 178, identifier:tbl; 179, identifier:insert; 180, argument_list; 180, 181; 181, identifier:groupobj; 182, return_statement; 182, 183; 183, identifier:tbl
def groupby(self, keyexpr, **outexprs): """simple prototype of group by, with support for expressions in the group-by clause and outputs @param keyexpr: grouping field and optional expression for computing the key value; if a string is passed @type keyexpr: string or tuple @param outexprs: named arguments describing one or more summary values to compute per key @type outexprs: callable, taking a sequence of objects as input and returning a single summary value """ if isinstance(keyexpr, basestring): keyattrs = keyexpr.split() keyfn = lambda o: tuple(getattr(o, k) for k in keyattrs) elif isinstance(keyexpr, tuple): keyattrs = (keyexpr[0],) keyfn = keyexpr[1] else: raise TypeError("keyexpr must be string or tuple") groupedobs = defaultdict(list) do_all(groupedobs[keyfn(ob)].append(ob) for ob in self.obs) tbl = Table() do_all(tbl.create_index(k, unique=(len(keyattrs) == 1)) for k in keyattrs) for key, recs in sorted(groupedobs.items()): groupobj = DataObject(**dict(zip(keyattrs, key))) do_all(setattr(groupobj, subkey, expr(recs)) for subkey, expr in outexprs.items()) tbl.insert(groupobj) return tbl
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 16; 2, function_name:dump_counts; 3, parameters; 3, 4; 3, 5; 3, 10; 3, 13; 4, identifier:self; 5, default_parameter; 5, 6; 5, 7; 6, identifier:out; 7, attribute; 7, 8; 7, 9; 8, identifier:sys; 9, identifier:stdout; 10, default_parameter; 10, 11; 10, 12; 11, identifier:count_fn; 12, identifier:len; 13, default_parameter; 13, 14; 13, 15; 14, identifier:colwidth; 15, integer:10; 16, block; 16, 17; 16, 19; 17, expression_statement; 17, 18; 18, comment; 19, if_statement; 19, 20; 19, 28; 19, 145; 19, 458; 20, comparison_operator:==; 20, 21; 20, 27; 21, call; 21, 22; 21, 23; 22, identifier:len; 23, argument_list; 23, 24; 24, attribute; 24, 25; 24, 26; 25, identifier:self; 26, identifier:_pivot_attrs; 27, integer:1; 28, block; 28, 29; 28, 45; 28, 65; 28, 69; 28, 73; 28, 110; 29, expression_statement; 29, 30; 30, call; 30, 31; 30, 34; 31, attribute; 31, 32; 31, 33; 32, identifier:out; 33, identifier:write; 34, argument_list; 34, 35; 35, binary_operator:%; 35, 36; 35, 37; 36, string:"Pivot: %s\n"; 37, call; 37, 38; 37, 41; 38, attribute; 38, 39; 38, 40; 39, string:','; 40, identifier:join; 41, argument_list; 41, 42; 42, attribute; 42, 43; 42, 44; 43, identifier:self; 44, identifier:_pivot_attrs; 45, expression_statement; 45, 46; 46, assignment; 46, 47; 46, 48; 47, identifier:maxkeylen; 48, call; 48, 49; 48, 50; 49, identifier:max; 50, generator_expression; 50, 51; 50, 58; 51, call; 51, 52; 51, 53; 52, identifier:len; 53, argument_list; 53, 54; 54, call; 54, 55; 54, 56; 55, identifier:str; 56, argument_list; 56, 57; 57, identifier:k; 58, for_in_clause; 58, 59; 58, 60; 59, identifier:k; 60, call; 60, 61; 60, 64; 61, attribute; 61, 62; 61, 63; 62, identifier:self; 63, identifier:keys; 64, argument_list; 65, expression_statement; 65, 66; 66, assignment; 66, 67; 66, 68; 67, identifier:maxvallen; 68, identifier:colwidth; 69, expression_statement; 69, 70; 70, assignment; 70, 71; 70, 72; 71, identifier:keytally; 72, dictionary; 73, for_statement; 73, 74; 73, 77; 73, 82; 74, pattern_list; 74, 75; 74, 76; 75, identifier:k; 76, identifier:sub; 77, call; 77, 78; 77, 81; 78, attribute; 78, 79; 78, 80; 79, identifier:self; 80, identifier:items; 81, argument_list; 82, block; 82, 83; 82, 90; 82, 104; 83, expression_statement; 83, 84; 84, assignment; 84, 85; 84, 86; 85, identifier:sub_v; 86, call; 86, 87; 86, 88; 87, identifier:count_fn; 88, argument_list; 88, 89; 89, identifier:sub; 90, expression_statement; 90, 91; 91, assignment; 91, 92; 91, 93; 92, identifier:maxvallen; 93, call; 93, 94; 93, 95; 94, identifier:max; 95, argument_list; 95, 96; 95, 97; 96, identifier:maxvallen; 97, call; 97, 98; 97, 99; 98, identifier:len; 99, argument_list; 99, 100; 100, call; 100, 101; 100, 102; 101, identifier:str; 102, argument_list; 102, 103; 103, identifier:sub_v; 104, expression_statement; 104, 105; 105, assignment; 105, 106; 105, 109; 106, subscript; 106, 107; 106, 108; 107, identifier:keytally; 108, identifier:k; 109, identifier:sub_v; 110, for_statement; 110, 111; 110, 114; 110, 119; 111, pattern_list; 111, 112; 111, 113; 112, identifier:k; 113, identifier:sub; 114, call; 114, 115; 114, 118; 115, attribute; 115, 116; 115, 117; 116, identifier:self; 117, identifier:items; 118, argument_list; 119, block; 119, 120; 119, 132; 120, expression_statement; 120, 121; 121, call; 121, 122; 121, 125; 122, attribute; 122, 123; 122, 124; 123, identifier:out; 124, identifier:write; 125, argument_list; 125, 126; 126, binary_operator:%; 126, 127; 126, 128; 127, string:"%-*.*s "; 128, tuple; 128, 129; 128, 130; 128, 131; 129, identifier:maxkeylen; 130, identifier:maxkeylen; 131, identifier:k; 132, expression_statement; 132, 133; 133, call; 133, 134; 133, 137; 134, attribute; 134, 135; 134, 136; 135, identifier:out; 136, identifier:write; 137, argument_list; 137, 138; 138, binary_operator:%; 138, 139; 138, 140; 139, string:"%*s\n"; 140, tuple; 140, 141; 140, 142; 141, identifier:maxvallen; 142, subscript; 142, 143; 142, 144; 143, identifier:keytally; 144, identifier:k; 145, elif_clause; 145, 146; 145, 154; 146, comparison_operator:==; 146, 147; 146, 153; 147, call; 147, 148; 147, 149; 148, identifier:len; 149, argument_list; 149, 150; 150, attribute; 150, 151; 150, 152; 151, identifier:self; 152, identifier:_pivot_attrs; 153, integer:2; 154, block; 154, 155; 154, 171; 154, 195; 154, 223; 154, 243; 154, 254; 154, 282; 154, 293; 154, 395; 154, 407; 154, 435; 155, expression_statement; 155, 156; 156, call; 156, 157; 156, 160; 157, attribute; 157, 158; 157, 159; 158, identifier:out; 159, identifier:write; 160, argument_list; 160, 161; 161, binary_operator:%; 161, 162; 161, 163; 162, string:"Pivot: %s\n"; 163, call; 163, 164; 163, 167; 164, attribute; 164, 165; 164, 166; 165, string:','; 166, identifier:join; 167, argument_list; 167, 168; 168, attribute; 168, 169; 168, 170; 169, identifier:self; 170, identifier:_pivot_attrs; 171, expression_statement; 171, 172; 172, assignment; 172, 173; 172, 174; 173, identifier:maxkeylen; 174, call; 174, 175; 174, 176; 175, identifier:max; 176, argument_list; 176, 177; 176, 194; 177, call; 177, 178; 177, 179; 178, identifier:max; 179, generator_expression; 179, 180; 179, 187; 180, call; 180, 181; 180, 182; 181, identifier:len; 182, argument_list; 182, 183; 183, call; 183, 184; 183, 185; 184, identifier:str; 185, argument_list; 185, 186; 186, identifier:k; 187, for_in_clause; 187, 188; 187, 189; 188, identifier:k; 189, call; 189, 190; 189, 193; 190, attribute; 190, 191; 190, 192; 191, identifier:self; 192, identifier:keys; 193, argument_list; 194, integer:5; 195, expression_statement; 195, 196; 196, assignment; 196, 197; 196, 198; 197, identifier:maxvallen; 198, call; 198, 199; 198, 200; 199, identifier:max; 200, argument_list; 200, 201; 200, 222; 201, call; 201, 202; 201, 203; 202, identifier:max; 203, generator_expression; 203, 204; 203, 211; 204, call; 204, 205; 204, 206; 205, identifier:len; 206, argument_list; 206, 207; 207, call; 207, 208; 207, 209; 208, identifier:str; 209, argument_list; 209, 210; 210, identifier:k; 211, for_in_clause; 211, 212; 211, 213; 212, identifier:k; 213, call; 213, 214; 213, 221; 214, attribute; 214, 215; 214, 220; 215, subscript; 215, 216; 215, 219; 216, attribute; 216, 217; 216, 218; 217, identifier:self; 218, identifier:subtables; 219, integer:0; 220, identifier:keys; 221, argument_list; 222, identifier:colwidth; 223, expression_statement; 223, 224; 224, assignment; 224, 225; 224, 226; 225, identifier:keytally; 226, call; 226, 227; 226, 228; 227, identifier:dict; 228, generator_expression; 228, 229; 228, 232; 229, tuple; 229, 230; 229, 231; 230, identifier:k; 231, integer:0; 232, for_in_clause; 232, 233; 232, 234; 233, identifier:k; 234, call; 234, 235; 234, 242; 235, attribute; 235, 236; 235, 241; 236, subscript; 236, 237; 236, 240; 237, attribute; 237, 238; 237, 239; 238, identifier:self; 239, identifier:subtables; 240, integer:0; 241, identifier:keys; 242, argument_list; 243, expression_statement; 243, 244; 244, call; 244, 245; 244, 248; 245, attribute; 245, 246; 245, 247; 246, identifier:out; 247, identifier:write; 248, argument_list; 248, 249; 249, binary_operator:%; 249, 250; 249, 251; 250, string:"%*s "; 251, tuple; 251, 252; 251, 253; 252, identifier:maxkeylen; 253, string:''; 254, expression_statement; 254, 255; 255, call; 255, 256; 255, 259; 256, attribute; 256, 257; 256, 258; 257, identifier:out; 258, identifier:write; 259, argument_list; 259, 260; 260, call; 260, 261; 260, 264; 261, attribute; 261, 262; 261, 263; 262, string:' '; 263, identifier:join; 264, generator_expression; 264, 265; 264, 271; 265, binary_operator:%; 265, 266; 265, 267; 266, string:"%*.*s"; 267, tuple; 267, 268; 267, 269; 267, 270; 268, identifier:maxvallen; 269, identifier:maxvallen; 270, identifier:k; 271, for_in_clause; 271, 272; 271, 273; 272, identifier:k; 273, call; 273, 274; 273, 281; 274, attribute; 274, 275; 274, 280; 275, subscript; 275, 276; 275, 279; 276, attribute; 276, 277; 276, 278; 277, identifier:self; 278, identifier:subtables; 279, integer:0; 280, identifier:keys; 281, argument_list; 282, expression_statement; 282, 283; 283, call; 283, 284; 283, 287; 284, attribute; 284, 285; 284, 286; 285, identifier:out; 286, identifier:write; 287, argument_list; 287, 288; 288, binary_operator:%; 288, 289; 288, 290; 289, string:' %*s\n'; 290, tuple; 290, 291; 290, 292; 291, identifier:maxvallen; 292, string:'Total'; 293, for_statement; 293, 294; 293, 297; 293, 302; 294, pattern_list; 294, 295; 294, 296; 295, identifier:k; 296, identifier:sub; 297, call; 297, 298; 297, 301; 298, attribute; 298, 299; 298, 300; 299, identifier:self; 300, identifier:items; 301, argument_list; 302, block; 302, 303; 302, 315; 302, 363; 302, 370; 302, 384; 303, expression_statement; 303, 304; 304, call; 304, 305; 304, 308; 305, attribute; 305, 306; 305, 307; 306, identifier:out; 307, identifier:write; 308, argument_list; 308, 309; 309, binary_operator:%; 309, 310; 309, 311; 310, string:"%-*.*s "; 311, tuple; 311, 312; 311, 313; 311, 314; 312, identifier:maxkeylen; 313, identifier:maxkeylen; 314, identifier:k; 315, for_statement; 315, 316; 315, 319; 315, 324; 316, pattern_list; 316, 317; 316, 318; 317, identifier:kk; 318, identifier:ssub; 319, call; 319, 320; 319, 323; 320, attribute; 320, 321; 320, 322; 321, identifier:sub; 322, identifier:items; 323, argument_list; 324, block; 324, 325; 324, 332; 324, 343; 324, 349; 325, expression_statement; 325, 326; 326, assignment; 326, 327; 326, 328; 327, identifier:ssub_v; 328, call; 328, 329; 328, 330; 329, identifier:count_fn; 330, argument_list; 330, 331; 331, identifier:ssub; 332, expression_statement; 332, 333; 333, call; 333, 334; 333, 337; 334, attribute; 334, 335; 334, 336; 335, identifier:out; 336, identifier:write; 337, argument_list; 337, 338; 338, binary_operator:%; 338, 339; 338, 340; 339, string:"%*d "; 340, tuple; 340, 341; 340, 342; 341, identifier:maxvallen; 342, identifier:ssub_v; 343, expression_statement; 343, 344; 344, augmented_assignment:+=; 344, 345; 344, 348; 345, subscript; 345, 346; 345, 347; 346, identifier:keytally; 347, identifier:kk; 348, identifier:ssub_v; 349, expression_statement; 349, 350; 350, assignment; 350, 351; 350, 352; 351, identifier:maxvallen; 352, call; 352, 353; 352, 354; 353, identifier:max; 354, argument_list; 354, 355; 354, 356; 355, identifier:maxvallen; 356, call; 356, 357; 356, 358; 357, identifier:len; 358, argument_list; 358, 359; 359, call; 359, 360; 359, 361; 360, identifier:str; 361, argument_list; 361, 362; 362, identifier:ssub_v; 363, expression_statement; 363, 364; 364, assignment; 364, 365; 364, 366; 365, identifier:sub_v; 366, call; 366, 367; 366, 368; 367, identifier:count_fn; 368, argument_list; 368, 369; 369, identifier:sub; 370, expression_statement; 370, 371; 371, assignment; 371, 372; 371, 373; 372, identifier:maxvallen; 373, call; 373, 374; 373, 375; 374, identifier:max; 375, argument_list; 375, 376; 375, 377; 376, identifier:maxvallen; 377, call; 377, 378; 377, 379; 378, identifier:len; 379, argument_list; 379, 380; 380, call; 380, 381; 380, 382; 381, identifier:str; 382, argument_list; 382, 383; 383, identifier:sub_v; 384, expression_statement; 384, 385; 385, call; 385, 386; 385, 389; 386, attribute; 386, 387; 386, 388; 387, identifier:out; 388, identifier:write; 389, argument_list; 389, 390; 390, binary_operator:%; 390, 391; 390, 392; 391, string:"%*d\n"; 392, tuple; 392, 393; 392, 394; 393, identifier:maxvallen; 394, identifier:sub_v; 395, expression_statement; 395, 396; 396, call; 396, 397; 396, 400; 397, attribute; 397, 398; 397, 399; 398, identifier:out; 399, identifier:write; 400, argument_list; 400, 401; 401, binary_operator:%; 401, 402; 401, 403; 402, string:'%-*.*s '; 403, tuple; 403, 404; 403, 405; 403, 406; 404, identifier:maxkeylen; 405, identifier:maxkeylen; 406, string:"Total"; 407, expression_statement; 407, 408; 408, call; 408, 409; 408, 412; 409, attribute; 409, 410; 409, 411; 410, identifier:out; 411, identifier:write; 412, argument_list; 412, 413; 413, call; 413, 414; 413, 417; 414, attribute; 414, 415; 414, 416; 415, string:' '; 416, identifier:join; 417, generator_expression; 417, 418; 417, 423; 418, binary_operator:%; 418, 419; 418, 420; 419, string:"%*d"; 420, tuple; 420, 421; 420, 422; 421, identifier:maxvallen; 422, identifier:tally; 423, for_in_clause; 423, 424; 423, 427; 424, pattern_list; 424, 425; 424, 426; 425, identifier:k; 426, identifier:tally; 427, call; 427, 428; 427, 429; 428, identifier:sorted; 429, argument_list; 429, 430; 430, call; 430, 431; 430, 434; 431, attribute; 431, 432; 431, 433; 432, identifier:keytally; 433, identifier:items; 434, argument_list; 435, expression_statement; 435, 436; 436, call; 436, 437; 436, 440; 437, attribute; 437, 438; 437, 439; 438, identifier:out; 439, identifier:write; 440, argument_list; 440, 441; 441, binary_operator:%; 441, 442; 441, 443; 442, string:" %*d\n"; 443, tuple; 443, 444; 443, 445; 444, identifier:maxvallen; 445, call; 445, 446; 445, 447; 446, identifier:sum; 447, generator_expression; 447, 448; 447, 449; 448, identifier:tally; 449, for_in_clause; 449, 450; 449, 453; 450, pattern_list; 450, 451; 450, 452; 451, identifier:k; 452, identifier:tally; 453, call; 453, 454; 453, 457; 454, attribute; 454, 455; 454, 456; 455, identifier:keytally; 456, identifier:items; 457, argument_list; 458, else_clause; 458, 459; 459, block; 459, 460; 460, raise_statement; 460, 461; 461, call; 461, 462; 461, 463; 462, identifier:ValueError; 463, argument_list; 463, 464; 464, string:"can only dump summary counts for 1 or 2-attribute pivots"
def dump_counts(self, out=sys.stdout, count_fn=len, colwidth=10): """Dump out the summary counts of entries in this pivot table as a tabular listing. @param out: output stream to write to @param count_fn: (default=len) function for computing value for each pivot cell @param colwidth: (default=10) """ if len(self._pivot_attrs) == 1: out.write("Pivot: %s\n" % ','.join(self._pivot_attrs)) maxkeylen = max(len(str(k)) for k in self.keys()) maxvallen = colwidth keytally = {} for k, sub in self.items(): sub_v = count_fn(sub) maxvallen = max(maxvallen, len(str(sub_v))) keytally[k] = sub_v for k, sub in self.items(): out.write("%-*.*s " % (maxkeylen, maxkeylen, k)) out.write("%*s\n" % (maxvallen, keytally[k])) elif len(self._pivot_attrs) == 2: out.write("Pivot: %s\n" % ','.join(self._pivot_attrs)) maxkeylen = max(max(len(str(k)) for k in self.keys()), 5) maxvallen = max(max(len(str(k)) for k in self.subtables[0].keys()), colwidth) keytally = dict((k, 0) for k in self.subtables[0].keys()) out.write("%*s " % (maxkeylen, '')) out.write(' '.join("%*.*s" % (maxvallen, maxvallen, k) for k in self.subtables[0].keys())) out.write(' %*s\n' % (maxvallen, 'Total')) for k, sub in self.items(): out.write("%-*.*s " % (maxkeylen, maxkeylen, k)) for kk, ssub in sub.items(): ssub_v = count_fn(ssub) out.write("%*d " % (maxvallen, ssub_v)) keytally[kk] += ssub_v maxvallen = max(maxvallen, len(str(ssub_v))) sub_v = count_fn(sub) maxvallen = max(maxvallen, len(str(sub_v))) out.write("%*d\n" % (maxvallen, sub_v)) out.write('%-*.*s ' % (maxkeylen, maxkeylen, "Total")) out.write(' '.join("%*d" % (maxvallen, tally) for k, tally in sorted(keytally.items()))) out.write(" %*d\n" % (maxvallen, sum(tally for k, tally in keytally.items()))) else: raise ValueError("can only dump summary counts for 1 or 2-attribute pivots")
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 14; 2, function_name:as_table; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 4, identifier:self; 5, default_parameter; 5, 6; 5, 7; 6, identifier:fn; 7, None; 8, default_parameter; 8, 9; 8, 10; 9, identifier:col; 10, None; 11, default_parameter; 11, 12; 11, 13; 12, identifier:col_label; 13, None; 14, block; 14, 15; 14, 17; 14, 26; 14, 44; 14, 50; 14, 51; 14, 66; 14, 310; 15, expression_statement; 15, 16; 16, comment; 17, if_statement; 17, 18; 17, 21; 18, comparison_operator:is; 18, 19; 18, 20; 19, identifier:col_label; 20, None; 21, block; 21, 22; 22, expression_statement; 22, 23; 23, assignment; 23, 24; 23, 25; 24, identifier:col_label; 25, identifier:col; 26, if_statement; 26, 27; 26, 30; 27, comparison_operator:is; 27, 28; 27, 29; 28, identifier:fn; 29, None; 30, block; 30, 31; 30, 35; 31, expression_statement; 31, 32; 32, assignment; 32, 33; 32, 34; 33, identifier:fn; 34, identifier:len; 35, if_statement; 35, 36; 35, 39; 36, comparison_operator:is; 36, 37; 36, 38; 37, identifier:col_label; 38, None; 39, block; 39, 40; 40, expression_statement; 40, 41; 41, assignment; 41, 42; 41, 43; 42, identifier:col_label; 43, string:'count'; 44, expression_statement; 44, 45; 45, assignment; 45, 46; 45, 47; 46, identifier:ret; 47, call; 47, 48; 47, 49; 48, identifier:Table; 49, argument_list; 50, comment; 51, expression_statement; 51, 52; 52, call; 52, 53; 52, 54; 53, identifier:do_all; 54, generator_expression; 54, 55; 54, 61; 55, call; 55, 56; 55, 59; 56, attribute; 56, 57; 56, 58; 57, identifier:ret; 58, identifier:create_index; 59, argument_list; 59, 60; 60, identifier:attr; 61, for_in_clause; 61, 62; 61, 63; 62, identifier:attr; 63, attribute; 63, 64; 63, 65; 64, identifier:self; 65, identifier:_pivot_attrs; 66, if_statement; 66, 67; 66, 75; 66, 145; 66, 221; 66, 303; 67, comparison_operator:==; 67, 68; 67, 74; 68, call; 68, 69; 68, 70; 69, identifier:len; 70, argument_list; 70, 71; 71, attribute; 71, 72; 71, 73; 72, identifier:self; 73, identifier:_pivot_attrs; 74, integer:1; 75, block; 75, 76; 76, for_statement; 76, 77; 76, 78; 76, 81; 77, identifier:sub; 78, attribute; 78, 79; 78, 80; 79, identifier:self; 80, identifier:subtables; 81, block; 81, 82; 81, 93; 81, 100; 81, 134; 82, expression_statement; 82, 83; 83, assignment; 83, 84; 83, 87; 84, pattern_list; 84, 85; 84, 86; 85, identifier:subattr; 86, identifier:subval; 87, subscript; 87, 88; 87, 91; 88, attribute; 88, 89; 88, 90; 89, identifier:sub; 90, identifier:_attr_path; 91, unary_operator:-; 91, 92; 92, integer:1; 93, expression_statement; 93, 94; 94, assignment; 94, 95; 94, 96; 95, identifier:attrdict; 96, dictionary; 96, 97; 97, pair; 97, 98; 97, 99; 98, identifier:subattr; 99, identifier:subval; 100, if_statement; 100, 101; 100, 108; 100, 118; 101, boolean_operator:or; 101, 102; 101, 105; 102, comparison_operator:is; 102, 103; 102, 104; 103, identifier:col; 104, None; 105, comparison_operator:is; 105, 106; 105, 107; 106, identifier:fn; 107, identifier:len; 108, block; 108, 109; 109, expression_statement; 109, 110; 110, assignment; 110, 111; 110, 114; 111, subscript; 111, 112; 111, 113; 112, identifier:attrdict; 113, identifier:col_label; 114, call; 114, 115; 114, 116; 115, identifier:fn; 116, argument_list; 116, 117; 117, identifier:sub; 118, else_clause; 118, 119; 119, block; 119, 120; 120, expression_statement; 120, 121; 121, assignment; 121, 122; 121, 125; 122, subscript; 122, 123; 122, 124; 123, identifier:attrdict; 124, identifier:col_label; 125, call; 125, 126; 125, 127; 126, identifier:fn; 127, generator_expression; 127, 128; 127, 131; 128, subscript; 128, 129; 128, 130; 129, identifier:s; 130, identifier:col; 131, for_in_clause; 131, 132; 131, 133; 132, identifier:s; 133, identifier:sub; 134, expression_statement; 134, 135; 135, call; 135, 136; 135, 139; 136, attribute; 136, 137; 136, 138; 137, identifier:ret; 138, identifier:insert; 139, argument_list; 139, 140; 140, call; 140, 141; 140, 142; 141, identifier:DataObject; 142, argument_list; 142, 143; 143, dictionary_splat; 143, 144; 144, identifier:attrdict; 145, elif_clause; 145, 146; 145, 154; 146, comparison_operator:==; 146, 147; 146, 153; 147, call; 147, 148; 147, 149; 148, identifier:len; 149, argument_list; 149, 150; 150, attribute; 150, 151; 150, 152; 151, identifier:self; 152, identifier:_pivot_attrs; 153, integer:2; 154, block; 154, 155; 155, for_statement; 155, 156; 155, 157; 155, 160; 156, identifier:sub; 157, attribute; 157, 158; 157, 159; 158, identifier:self; 159, identifier:subtables; 160, block; 160, 161; 161, for_statement; 161, 162; 161, 163; 161, 166; 162, identifier:ssub; 163, attribute; 163, 164; 163, 165; 164, identifier:sub; 165, identifier:subtables; 166, block; 166, 167; 166, 176; 166, 210; 167, expression_statement; 167, 168; 168, assignment; 168, 169; 168, 170; 169, identifier:attrdict; 170, call; 170, 171; 170, 172; 171, identifier:dict; 172, argument_list; 172, 173; 173, attribute; 173, 174; 173, 175; 174, identifier:ssub; 175, identifier:_attr_path; 176, if_statement; 176, 177; 176, 184; 176, 194; 177, boolean_operator:or; 177, 178; 177, 181; 178, comparison_operator:is; 178, 179; 178, 180; 179, identifier:col; 180, None; 181, comparison_operator:is; 181, 182; 181, 183; 182, identifier:fn; 183, identifier:len; 184, block; 184, 185; 185, expression_statement; 185, 186; 186, assignment; 186, 187; 186, 190; 187, subscript; 187, 188; 187, 189; 188, identifier:attrdict; 189, identifier:col_label; 190, call; 190, 191; 190, 192; 191, identifier:fn; 192, argument_list; 192, 193; 193, identifier:ssub; 194, else_clause; 194, 195; 195, block; 195, 196; 196, expression_statement; 196, 197; 197, assignment; 197, 198; 197, 201; 198, subscript; 198, 199; 198, 200; 199, identifier:attrdict; 200, identifier:col_label; 201, call; 201, 202; 201, 203; 202, identifier:fn; 203, generator_expression; 203, 204; 203, 207; 204, subscript; 204, 205; 204, 206; 205, identifier:s; 206, identifier:col; 207, for_in_clause; 207, 208; 207, 209; 208, identifier:s; 209, identifier:ssub; 210, expression_statement; 210, 211; 211, call; 211, 212; 211, 215; 212, attribute; 212, 213; 212, 214; 213, identifier:ret; 214, identifier:insert; 215, argument_list; 215, 216; 216, call; 216, 217; 216, 218; 217, identifier:DataObject; 218, argument_list; 218, 219; 219, dictionary_splat; 219, 220; 220, identifier:attrdict; 221, elif_clause; 221, 222; 221, 230; 222, comparison_operator:==; 222, 223; 222, 229; 223, call; 223, 224; 223, 225; 224, identifier:len; 225, argument_list; 225, 226; 226, attribute; 226, 227; 226, 228; 227, identifier:self; 228, identifier:_pivot_attrs; 229, integer:3; 230, block; 230, 231; 231, for_statement; 231, 232; 231, 233; 231, 236; 232, identifier:sub; 233, attribute; 233, 234; 233, 235; 234, identifier:self; 235, identifier:subtables; 236, block; 236, 237; 237, for_statement; 237, 238; 237, 239; 237, 242; 238, identifier:ssub; 239, attribute; 239, 240; 239, 241; 240, identifier:sub; 241, identifier:subtables; 242, block; 242, 243; 243, for_statement; 243, 244; 243, 245; 243, 248; 244, identifier:sssub; 245, attribute; 245, 246; 245, 247; 246, identifier:ssub; 247, identifier:subtables; 248, block; 248, 249; 248, 258; 248, 292; 249, expression_statement; 249, 250; 250, assignment; 250, 251; 250, 252; 251, identifier:attrdict; 252, call; 252, 253; 252, 254; 253, identifier:dict; 254, argument_list; 254, 255; 255, attribute; 255, 256; 255, 257; 256, identifier:sssub; 257, identifier:_attr_path; 258, if_statement; 258, 259; 258, 266; 258, 276; 259, boolean_operator:or; 259, 260; 259, 263; 260, comparison_operator:is; 260, 261; 260, 262; 261, identifier:col; 262, None; 263, comparison_operator:is; 263, 264; 263, 265; 264, identifier:fn; 265, identifier:len; 266, block; 266, 267; 267, expression_statement; 267, 268; 268, assignment; 268, 269; 268, 272; 269, subscript; 269, 270; 269, 271; 270, identifier:attrdict; 271, identifier:col_label; 272, call; 272, 273; 272, 274; 273, identifier:fn; 274, argument_list; 274, 275; 275, identifier:sssub; 276, else_clause; 276, 277; 277, block; 277, 278; 278, expression_statement; 278, 279; 279, assignment; 279, 280; 279, 283; 280, subscript; 280, 281; 280, 282; 281, identifier:attrdict; 282, identifier:col_label; 283, call; 283, 284; 283, 285; 284, identifier:fn; 285, generator_expression; 285, 286; 285, 289; 286, subscript; 286, 287; 286, 288; 287, identifier:s; 288, identifier:col; 289, for_in_clause; 289, 290; 289, 291; 290, identifier:s; 291, identifier:sssub; 292, expression_statement; 292, 293; 293, call; 293, 294; 293, 297; 294, attribute; 294, 295; 294, 296; 295, identifier:ret; 296, identifier:insert; 297, argument_list; 297, 298; 298, call; 298, 299; 298, 300; 299, identifier:DataObject; 300, argument_list; 300, 301; 301, dictionary_splat; 301, 302; 302, identifier:attrdict; 303, else_clause; 303, 304; 304, block; 304, 305; 305, raise_statement; 305, 306; 306, call; 306, 307; 306, 308; 307, identifier:ValueError; 308, argument_list; 308, 309; 309, string:"can only dump summary counts for 1 or 2-attribute pivots"; 310, return_statement; 310, 311; 311, identifier:ret
def as_table(self, fn=None, col=None, col_label=None): """Dump out the summary counts of this pivot table as a Table. """ if col_label is None: col_label = col if fn is None: fn = len if col_label is None: col_label = 'count' ret = Table() # topattr = self._pivot_attrs[0] do_all(ret.create_index(attr) for attr in self._pivot_attrs) if len(self._pivot_attrs) == 1: for sub in self.subtables: subattr, subval = sub._attr_path[-1] attrdict = {subattr: subval} if col is None or fn is len: attrdict[col_label] = fn(sub) else: attrdict[col_label] = fn(s[col] for s in sub) ret.insert(DataObject(**attrdict)) elif len(self._pivot_attrs) == 2: for sub in self.subtables: for ssub in sub.subtables: attrdict = dict(ssub._attr_path) if col is None or fn is len: attrdict[col_label] = fn(ssub) else: attrdict[col_label] = fn(s[col] for s in ssub) ret.insert(DataObject(**attrdict)) elif len(self._pivot_attrs) == 3: for sub in self.subtables: for ssub in sub.subtables: for sssub in ssub.subtables: attrdict = dict(sssub._attr_path) if col is None or fn is len: attrdict[col_label] = fn(sssub) else: attrdict[col_label] = fn(s[col] for s in sssub) ret.insert(DataObject(**attrdict)) else: raise ValueError("can only dump summary counts for 1 or 2-attribute pivots") return ret
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 7; 2, function_name:remove_edge; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:self; 5, identifier:u; 6, identifier:v; 7, block; 7, 8; 7, 10; 7, 11; 7, 20; 7, 30; 7, 36; 7, 37; 7, 54; 7, 55; 7, 56; 7, 85; 7, 86; 7, 87; 7, 88; 8, expression_statement; 8, 9; 9, comment; 10, comment; 11, expression_statement; 11, 12; 12, call; 12, 13; 12, 14; 13, identifier:print; 14, argument_list; 14, 15; 15, binary_operator:%; 15, 16; 15, 17; 16, string:'Dynamically removing uv=(%r, %r)'; 17, tuple; 17, 18; 17, 19; 18, identifier:u; 19, identifier:v; 20, expression_statement; 20, 21; 21, call; 21, 22; 21, 27; 22, attribute; 22, 23; 22, 26; 23, attribute; 23, 24; 23, 25; 24, identifier:self; 25, identifier:graph; 26, identifier:remove_edge; 27, argument_list; 27, 28; 27, 29; 28, identifier:u; 29, identifier:v; 30, expression_statement; 30, 31; 31, assignment; 31, 32; 31, 33; 32, identifier:e; 33, tuple; 33, 34; 33, 35; 34, identifier:u; 35, identifier:v; 36, comment; 37, if_statement; 37, 38; 37, 50; 37, 51; 37, 52; 38, not_operator; 38, 39; 39, call; 39, 40; 39, 47; 40, attribute; 40, 41; 40, 46; 41, subscript; 41, 42; 41, 45; 42, attribute; 42, 43; 42, 44; 43, identifier:self; 44, identifier:forests; 45, integer:0; 46, identifier:has_edge; 47, argument_list; 47, 48; 47, 49; 48, identifier:u; 49, identifier:v; 50, comment; 51, comment; 52, block; 52, 53; 53, return_statement; 54, comment; 55, comment; 56, for_statement; 56, 57; 56, 58; 56, 72; 57, identifier:i; 58, call; 58, 59; 58, 60; 59, identifier:reversed; 60, argument_list; 60, 61; 61, call; 61, 62; 61, 63; 62, identifier:range; 63, argument_list; 63, 64; 63, 65; 64, integer:0; 65, binary_operator:+; 65, 66; 65, 71; 66, subscript; 66, 67; 66, 70; 67, attribute; 67, 68; 67, 69; 68, identifier:self; 69, identifier:level; 70, identifier:e; 71, integer:1; 72, block; 72, 73; 73, expression_statement; 73, 74; 74, call; 74, 75; 74, 82; 75, attribute; 75, 76; 75, 81; 76, subscript; 76, 77; 76, 80; 77, attribute; 77, 78; 77, 79; 78, identifier:self; 79, identifier:forests; 80, identifier:i; 81, identifier:remove_edge; 82, argument_list; 82, 83; 82, 84; 83, identifier:u; 84, identifier:v; 85, comment; 86, comment; 87, comment; 88, for_statement; 88, 89; 88, 90; 88, 104; 88, 105; 89, identifier:i; 90, call; 90, 91; 90, 92; 91, identifier:reversed; 92, argument_list; 92, 93; 93, call; 93, 94; 93, 95; 94, identifier:range; 95, argument_list; 95, 96; 95, 97; 96, integer:0; 97, binary_operator:+; 97, 98; 97, 103; 98, subscript; 98, 99; 98, 102; 99, attribute; 99, 100; 99, 101; 100, identifier:self; 101, identifier:level; 102, identifier:e; 103, integer:1; 104, comment; 105, block; 105, 106; 105, 119; 105, 134; 105, 147; 105, 162; 105, 163; 105, 164; 105, 184; 105, 185; 105, 186; 105, 193; 106, expression_statement; 106, 107; 107, assignment; 107, 108; 107, 109; 108, identifier:Tu; 109, call; 109, 110; 109, 117; 110, attribute; 110, 111; 110, 116; 111, subscript; 111, 112; 111, 115; 112, attribute; 112, 113; 112, 114; 113, identifier:self; 114, identifier:forests; 115, identifier:i; 116, identifier:subtree; 117, argument_list; 117, 118; 118, identifier:u; 119, expression_statement; 119, 120; 120, call; 120, 121; 120, 122; 121, identifier:print; 122, argument_list; 122, 123; 123, binary_operator:%; 123, 124; 123, 125; 124, string:'Tu = %r'; 125, tuple; 125, 126; 126, call; 126, 127; 126, 128; 127, identifier:list; 128, argument_list; 128, 129; 129, call; 129, 130; 129, 133; 130, attribute; 130, 131; 130, 132; 131, identifier:Tu; 132, identifier:nodes; 133, argument_list; 134, expression_statement; 134, 135; 135, assignment; 135, 136; 135, 137; 136, identifier:Tv; 137, call; 137, 138; 137, 145; 138, attribute; 138, 139; 138, 144; 139, subscript; 139, 140; 139, 143; 140, attribute; 140, 141; 140, 142; 141, identifier:self; 142, identifier:forests; 143, identifier:i; 144, identifier:subtree; 145, argument_list; 145, 146; 146, identifier:v; 147, expression_statement; 147, 148; 148, call; 148, 149; 148, 150; 149, identifier:print; 150, argument_list; 150, 151; 151, binary_operator:%; 151, 152; 151, 153; 152, string:'Tv = %r'; 153, tuple; 153, 154; 154, call; 154, 155; 154, 156; 155, identifier:list; 156, argument_list; 156, 157; 157, call; 157, 158; 157, 161; 158, attribute; 158, 159; 158, 160; 159, identifier:Tv; 160, identifier:nodes; 161, argument_list; 162, comment; 163, comment; 164, if_statement; 164, 165; 164, 174; 165, comparison_operator:>; 165, 166; 165, 170; 166, call; 166, 167; 166, 168; 167, identifier:len; 168, argument_list; 168, 169; 169, identifier:Tu; 170, call; 170, 171; 170, 172; 171, identifier:len; 172, argument_list; 172, 173; 173, identifier:Tv; 174, block; 174, 175; 174, 183; 175, expression_statement; 175, 176; 176, assignment; 176, 177; 176, 180; 177, pattern_list; 177, 178; 177, 179; 178, identifier:Tu; 179, identifier:Tv; 180, expression_list; 180, 181; 180, 182; 181, identifier:Tv; 182, identifier:Tu; 183, comment; 184, comment; 185, comment; 186, expression_statement; 186, 187; 187, assignment; 187, 188; 187, 189; 188, identifier:seen_; 189, call; 189, 190; 189, 191; 190, identifier:set; 191, argument_list; 191, 192; 192, list:[]; 193, for_statement; 193, 194; 193, 195; 193, 200; 193, 201; 193, 202; 194, identifier:x; 195, call; 195, 196; 195, 199; 196, attribute; 196, 197; 196, 198; 197, identifier:Tu; 198, identifier:nodes; 199, argument_list; 200, comment; 201, comment; 202, block; 202, 203; 202, 210; 203, expression_statement; 203, 204; 204, call; 204, 205; 204, 208; 205, attribute; 205, 206; 205, 207; 206, identifier:seen_; 207, identifier:add; 208, argument_list; 208, 209; 209, identifier:x; 210, for_statement; 210, 211; 210, 212; 210, 220; 211, identifier:y; 212, call; 212, 213; 212, 218; 213, attribute; 213, 214; 213, 217; 214, attribute; 214, 215; 214, 216; 215, identifier:self; 216, identifier:graph; 217, identifier:neighbors; 218, argument_list; 218, 219; 219, identifier:x; 220, block; 220, 221; 220, 227; 220, 228; 221, if_statement; 221, 222; 221, 225; 222, comparison_operator:in; 222, 223; 222, 224; 223, identifier:y; 224, identifier:seen_; 225, block; 225, 226; 226, continue_statement; 227, comment; 228, if_statement; 228, 229; 228, 232; 228, 308; 229, comparison_operator:in; 229, 230; 229, 231; 230, identifier:y; 231, identifier:Tv; 232, block; 232, 233; 232, 242; 232, 243; 232, 244; 232, 245; 232, 246; 232, 276; 232, 307; 233, expression_statement; 233, 234; 234, call; 234, 235; 234, 236; 235, identifier:print; 236, argument_list; 236, 237; 237, binary_operator:%; 237, 238; 237, 239; 238, string:'* Found replacement xy=(%r, %r)'; 239, tuple; 239, 240; 239, 241; 240, identifier:x; 241, identifier:y; 242, comment; 243, comment; 244, comment; 245, comment; 246, if_statement; 246, 247; 246, 257; 247, comparison_operator:==; 247, 248; 247, 254; 248, call; 248, 249; 248, 250; 249, identifier:len; 250, argument_list; 250, 251; 251, attribute; 251, 252; 251, 253; 252, identifier:self; 253, identifier:forests; 254, binary_operator:+; 254, 255; 254, 256; 255, identifier:i; 256, integer:1; 257, block; 257, 258; 258, expression_statement; 258, 259; 259, call; 259, 260; 259, 265; 260, attribute; 260, 261; 260, 264; 261, attribute; 261, 262; 261, 263; 262, identifier:self; 263, identifier:forests; 264, identifier:append; 265, argument_list; 265, 266; 266, call; 266, 267; 266, 268; 267, identifier:DummyEulerTourForest; 268, argument_list; 268, 269; 269, call; 269, 270; 269, 275; 270, attribute; 270, 271; 270, 274; 271, attribute; 271, 272; 271, 273; 272, identifier:self; 273, identifier:graph; 274, identifier:nodes; 275, argument_list; 276, for_statement; 276, 277; 276, 278; 276, 285; 277, identifier:j; 278, call; 278, 279; 278, 280; 279, identifier:range; 280, argument_list; 280, 281; 280, 282; 281, integer:0; 282, binary_operator:+; 282, 283; 282, 284; 283, identifier:i; 284, integer:2; 285, block; 285, 286; 285, 294; 285, 295; 286, expression_statement; 286, 287; 287, call; 287, 288; 287, 289; 288, identifier:print; 289, argument_list; 289, 290; 290, binary_operator:%; 290, 291; 290, 292; 291, string:'* Add replacment to F[j=%r]'; 292, tuple; 292, 293; 293, identifier:j; 294, comment; 295, expression_statement; 295, 296; 296, call; 296, 297; 296, 304; 297, attribute; 297, 298; 297, 303; 298, subscript; 298, 299; 298, 302; 299, attribute; 299, 300; 299, 301; 300, identifier:self; 301, identifier:forests; 302, identifier:j; 303, identifier:add_edge; 304, argument_list; 304, 305; 304, 306; 305, identifier:x; 306, identifier:y; 307, return_statement; 308, else_clause; 308, 309; 309, block; 309, 310; 309, 319; 309, 320; 309, 321; 309, 322; 309, 352; 309, 379; 309, 380; 310, expression_statement; 310, 311; 311, call; 311, 312; 311, 313; 312, identifier:print; 313, argument_list; 313, 314; 314, binary_operator:%; 314, 315; 314, 316; 315, string:'* Charging xy=(%r, %r)'; 316, tuple; 316, 317; 316, 318; 317, identifier:x; 318, identifier:y; 319, comment; 320, comment; 321, comment; 322, if_statement; 322, 323; 322, 333; 323, comparison_operator:==; 323, 324; 323, 330; 324, call; 324, 325; 324, 326; 325, identifier:len; 326, argument_list; 326, 327; 327, attribute; 327, 328; 327, 329; 328, identifier:self; 329, identifier:forests; 330, binary_operator:+; 330, 331; 330, 332; 331, identifier:i; 332, integer:1; 333, block; 333, 334; 334, expression_statement; 334, 335; 335, call; 335, 336; 335, 341; 336, attribute; 336, 337; 336, 340; 337, attribute; 337, 338; 337, 339; 338, identifier:self; 339, identifier:forests; 340, identifier:append; 341, argument_list; 341, 342; 342, call; 342, 343; 342, 344; 343, identifier:DummyEulerTourForest; 344, argument_list; 344, 345; 345, call; 345, 346; 345, 351; 346, attribute; 346, 347; 346, 350; 347, attribute; 347, 348; 347, 349; 348, identifier:self; 349, identifier:graph; 350, identifier:nodes; 351, argument_list; 352, if_statement; 352, 353; 352, 364; 353, call; 353, 354; 353, 361; 354, attribute; 354, 355; 354, 360; 355, subscript; 355, 356; 355, 359; 356, attribute; 356, 357; 356, 358; 357, identifier:self; 358, identifier:forests; 359, identifier:i; 360, identifier:has_edge; 361, argument_list; 361, 362; 361, 363; 362, identifier:x; 363, identifier:y; 364, block; 364, 365; 365, expression_statement; 365, 366; 366, call; 366, 367; 366, 376; 367, attribute; 367, 368; 367, 375; 368, subscript; 368, 369; 368, 372; 369, attribute; 369, 370; 369, 371; 370, identifier:self; 371, identifier:forests; 372, binary_operator:+; 372, 373; 372, 374; 373, identifier:i; 374, integer:1; 375, identifier:add_edge; 376, argument_list; 376, 377; 376, 378; 377, identifier:x; 378, identifier:y; 379, comment; 380, expression_statement; 380, 381; 381, assignment; 381, 382; 381, 389; 382, subscript; 382, 383; 382, 386; 383, attribute; 383, 384; 383, 385; 384, identifier:self; 385, identifier:level; 386, tuple; 386, 387; 386, 388; 387, identifier:x; 388, identifier:y; 389, binary_operator:+; 389, 390; 389, 391; 390, identifier:i; 391, integer:1
def remove_edge(self, u, v): """ Using notation where 0 is top level Intuitively speaking, when the level of a nontree edge is increased, it is because we have discovered that its end points are close enough in F to fit in a smaller tree on a higher level. """ # Remove (u, v) from represented graph print('Dynamically removing uv=(%r, %r)' % (u, v)) self.graph.remove_edge(u, v) e = (u, v) # Remove edge e = (u, v) from all graphs. if not self.forests[0].has_edge(u, v): # If (u, v) is a non-tree edge, simply delete it. # Nothing else to do. return # If (u, v) is a tree edge we delete it and search for a replacement. # Delete from all higher levels for i in reversed(range(0, self.level[e] + 1)): self.forests[i].remove_edge(u, v) # Determine if another edge that connects u and v exists. # (This must be an edge r, level[r] <= level[e]) # (Find max possible level[r] <= level[e]) for i in reversed(range(0, self.level[e] + 1)): # Tu != Tw b/c (u, v) was just deleted from all forests Tu = self.forests[i].subtree(u) print('Tu = %r' % (list(Tu.nodes()),)) Tv = self.forests[i].subtree(v) print('Tv = %r' % (list(Tv.nodes()),)) # Relabel so len(Tu) <= len(Tv) # This ensures len(Tu) < 2 ** (floor(log(n)) - i) if len(Tu) > len(Tv): Tu, Tv = Tv, Tu # Note len(Tu) <= 2 * (len(Tu) + len(Tv) + 1) # We can afford to push all of Tu's edges to the next level and # still preserve invariant 1. seen_ = set([]) for x in Tu.nodes(): # Visit all edges INCIDENT (in real graph) to nodes in Tu. # This lets us find non-tree edges to make a tree edge seen_.add(x) for y in self.graph.neighbors(x): if y in seen_: continue # print('Check replacement edge xy=(%r, %r)' % (x, y)) if y in Tv: print('* Found replacement xy=(%r, %r)' % (x, y)) # edge (x, y) is a replacement edge. # add (x, y) to prev forests F[0:i+1] # This is the only place edges are added to forets of # higher levels. if len(self.forests) == i + 1: self.forests.append(DummyEulerTourForest(self.graph.nodes())) for j in range(0, i + 2): print('* Add replacment to F[j=%r]' % (j,)) # Need euler tree augmentation for outgoing level edges self.forests[j].add_edge(x, y) return else: print('* Charging xy=(%r, %r)' % (x, y)) # charge --- add (x, y) to next level # this pays for our search in an amortized sense # (ie, the next search at this level wont consider this) if len(self.forests) == i + 1: self.forests.append(DummyEulerTourForest(self.graph.nodes())) if self.forests[i].has_edge(x, y): self.forests[i + 1].add_edge(x, y) # # assert False, 'we got it, should add it?' self.level[(x, y)] = i + 1
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 39; 2, function_name:get_stats_str; 3, parameters; 3, 4; 3, 7; 3, 10; 3, 13; 3, 16; 3, 19; 3, 22; 3, 25; 3, 28; 3, 31; 3, 34; 3, 37; 4, default_parameter; 4, 5; 4, 6; 5, identifier:list_; 6, None; 7, default_parameter; 7, 8; 7, 9; 8, identifier:newlines; 9, False; 10, default_parameter; 10, 11; 10, 12; 11, identifier:keys; 12, None; 13, default_parameter; 13, 14; 13, 15; 14, identifier:exclude_keys; 15, list:[]; 16, default_parameter; 16, 17; 16, 18; 17, identifier:lbl; 18, None; 19, default_parameter; 19, 20; 19, 21; 20, identifier:precision; 21, None; 22, default_parameter; 22, 23; 22, 24; 23, identifier:axis; 24, integer:0; 25, default_parameter; 25, 26; 25, 27; 26, identifier:stat_dict; 27, None; 28, default_parameter; 28, 29; 28, 30; 29, identifier:use_nan; 30, False; 31, default_parameter; 31, 32; 31, 33; 32, identifier:align; 33, False; 34, default_parameter; 34, 35; 34, 36; 35, identifier:use_median; 36, False; 37, dictionary_splat_pattern; 37, 38; 38, identifier:kwargs; 39, block; 39, 40; 39, 42; 39, 48; 39, 53; 39, 54; 39, 85; 39, 86; 39, 112; 39, 113; 39, 126; 39, 127; 39, 135; 39, 136; 39, 361; 39, 362; 39, 375; 39, 376; 39, 394; 39, 409; 39, 422; 40, expression_statement; 40, 41; 41, comment; 42, import_from_statement; 42, 43; 42, 46; 43, dotted_name; 43, 44; 43, 45; 44, identifier:utool; 45, identifier:util_str; 46, dotted_name; 46, 47; 47, identifier:repr4; 48, import_statement; 48, 49; 49, aliased_import; 49, 50; 49, 52; 50, dotted_name; 50, 51; 51, identifier:utool; 52, identifier:ut; 53, comment; 54, if_statement; 54, 55; 54, 58; 54, 75; 55, comparison_operator:is; 55, 56; 55, 57; 56, identifier:stat_dict; 57, None; 58, block; 58, 59; 59, expression_statement; 59, 60; 60, assignment; 60, 61; 60, 62; 61, identifier:stat_dict; 62, call; 62, 63; 62, 64; 63, identifier:get_stats; 64, argument_list; 64, 65; 64, 66; 64, 69; 64, 72; 65, identifier:list_; 66, keyword_argument; 66, 67; 66, 68; 67, identifier:axis; 68, identifier:axis; 69, keyword_argument; 69, 70; 69, 71; 70, identifier:use_nan; 71, identifier:use_nan; 72, keyword_argument; 72, 73; 72, 74; 73, identifier:use_median; 74, identifier:use_median; 75, else_clause; 75, 76; 76, block; 76, 77; 77, expression_statement; 77, 78; 78, assignment; 78, 79; 78, 80; 79, identifier:stat_dict; 80, call; 80, 81; 80, 84; 81, attribute; 81, 82; 81, 83; 82, identifier:stat_dict; 83, identifier:copy; 84, argument_list; 85, comment; 86, if_statement; 86, 87; 86, 90; 87, comparison_operator:is; 87, 88; 87, 89; 88, identifier:keys; 89, None; 90, block; 90, 91; 91, for_statement; 91, 92; 91, 93; 91, 102; 92, identifier:key; 93, call; 93, 94; 93, 95; 94, identifier:list; 95, argument_list; 95, 96; 96, call; 96, 97; 96, 100; 97, attribute; 97, 98; 97, 99; 98, identifier:six; 99, identifier:iterkeys; 100, argument_list; 100, 101; 101, identifier:stat_dict; 102, block; 102, 103; 103, if_statement; 103, 104; 103, 107; 104, comparison_operator:not; 104, 105; 104, 106; 105, identifier:key; 106, identifier:keys; 107, block; 107, 108; 108, delete_statement; 108, 109; 109, subscript; 109, 110; 109, 111; 110, identifier:stat_dict; 111, identifier:key; 112, comment; 113, for_statement; 113, 114; 113, 115; 113, 116; 114, identifier:key; 115, identifier:exclude_keys; 116, block; 116, 117; 117, if_statement; 117, 118; 117, 121; 118, comparison_operator:in; 118, 119; 118, 120; 119, identifier:key; 120, identifier:stat_dict; 121, block; 121, 122; 122, delete_statement; 122, 123; 123, subscript; 123, 124; 123, 125; 124, identifier:stat_dict; 125, identifier:key; 126, comment; 127, expression_statement; 127, 128; 128, assignment; 128, 129; 128, 130; 129, identifier:statstr_dict; 130, call; 130, 131; 130, 134; 131, attribute; 131, 132; 131, 133; 132, identifier:stat_dict; 133, identifier:copy; 134, argument_list; 135, comment; 136, if_statement; 136, 137; 136, 140; 137, comparison_operator:is; 137, 138; 137, 139; 138, identifier:precision; 139, None; 140, block; 140, 141; 140, 149; 140, 160; 141, assert_statement; 141, 142; 141, 148; 142, call; 142, 143; 142, 146; 143, attribute; 143, 144; 143, 145; 144, identifier:ut; 145, identifier:is_int; 146, argument_list; 146, 147; 147, identifier:precision; 148, string:'precision must be an integer'; 149, expression_statement; 149, 150; 150, assignment; 150, 151; 150, 152; 151, identifier:float_fmtstr; 152, binary_operator:+; 152, 153; 152, 159; 153, binary_operator:+; 153, 154; 153, 155; 154, string:'%.'; 155, call; 155, 156; 155, 157; 156, identifier:str; 157, argument_list; 157, 158; 158, identifier:precision; 159, string:'f'; 160, for_statement; 160, 161; 160, 162; 160, 171; 161, identifier:key; 162, call; 162, 163; 162, 164; 163, identifier:list; 164, argument_list; 164, 165; 165, call; 165, 166; 165, 169; 166, attribute; 166, 167; 166, 168; 167, identifier:six; 168, identifier:iterkeys; 169, argument_list; 169, 170; 170, identifier:statstr_dict; 171, block; 171, 172; 171, 178; 171, 187; 171, 246; 172, expression_statement; 172, 173; 173, assignment; 173, 174; 173, 175; 174, identifier:val; 175, subscript; 175, 176; 175, 177; 176, identifier:statstr_dict; 177, identifier:key; 178, expression_statement; 178, 179; 179, assignment; 179, 180; 179, 181; 180, identifier:isfloat; 181, call; 181, 182; 181, 185; 182, attribute; 182, 183; 182, 184; 183, identifier:ut; 184, identifier:is_float; 185, argument_list; 185, 186; 186, identifier:val; 187, if_statement; 187, 188; 187, 196; 188, boolean_operator:and; 188, 189; 188, 191; 189, not_operator; 189, 190; 190, identifier:isfloat; 191, call; 191, 192; 191, 193; 192, identifier:isinstance; 193, argument_list; 193, 194; 193, 195; 194, identifier:val; 195, identifier:list; 196, block; 196, 197; 196, 208; 197, expression_statement; 197, 198; 198, assignment; 198, 199; 198, 200; 199, identifier:type_list; 200, call; 200, 201; 200, 202; 201, identifier:list; 202, argument_list; 202, 203; 203, call; 203, 204; 203, 205; 204, identifier:map; 205, argument_list; 205, 206; 205, 207; 206, identifier:type; 207, identifier:val; 208, if_statement; 208, 209; 208, 222; 209, boolean_operator:and; 209, 210; 209, 216; 210, comparison_operator:>; 210, 211; 210, 215; 211, call; 211, 212; 211, 213; 212, identifier:len; 213, argument_list; 213, 214; 214, identifier:type_list; 215, integer:0; 216, call; 216, 217; 216, 220; 217, attribute; 217, 218; 217, 219; 218, identifier:ut; 219, identifier:allsame; 220, argument_list; 220, 221; 221, identifier:type_list; 222, block; 222, 223; 223, if_statement; 223, 224; 223, 232; 224, call; 224, 225; 224, 228; 225, attribute; 225, 226; 225, 227; 226, identifier:ut; 227, identifier:is_float; 228, argument_list; 228, 229; 229, subscript; 229, 230; 229, 231; 230, identifier:val; 231, integer:0; 232, block; 232, 233; 232, 237; 233, expression_statement; 233, 234; 234, assignment; 234, 235; 234, 236; 235, identifier:isfloat; 236, True; 237, expression_statement; 237, 238; 238, assignment; 238, 239; 238, 240; 239, identifier:val; 240, call; 240, 241; 240, 244; 241, attribute; 241, 242; 241, 243; 242, identifier:np; 243, identifier:array; 244, argument_list; 244, 245; 245, identifier:val; 246, if_statement; 246, 247; 246, 248; 246, 324; 247, identifier:isfloat; 248, block; 248, 249; 248, 291; 248, 318; 249, if_statement; 249, 250; 249, 257; 249, 283; 250, call; 250, 251; 250, 252; 251, identifier:isinstance; 252, argument_list; 252, 253; 252, 254; 253, identifier:val; 254, attribute; 254, 255; 254, 256; 255, identifier:np; 256, identifier:ndarray; 257, block; 257, 258; 257, 282; 258, expression_statement; 258, 259; 259, assignment; 259, 260; 259, 261; 260, identifier:strval; 261, call; 261, 262; 261, 280; 262, attribute; 262, 263; 262, 279; 263, call; 263, 264; 263, 276; 264, attribute; 264, 265; 264, 275; 265, call; 265, 266; 265, 267; 266, identifier:str; 267, argument_list; 267, 268; 268, list_comprehension; 268, 269; 268, 272; 269, binary_operator:%; 269, 270; 269, 271; 270, identifier:float_fmtstr; 271, identifier:v; 272, for_in_clause; 272, 273; 272, 274; 273, identifier:v; 274, identifier:val; 275, identifier:replace; 276, argument_list; 276, 277; 276, 278; 277, string:'\''; 278, string:''; 279, identifier:lstrip; 280, argument_list; 280, 281; 281, string:'u'; 282, comment; 283, else_clause; 283, 284; 284, block; 284, 285; 285, expression_statement; 285, 286; 286, assignment; 286, 287; 286, 288; 287, identifier:strval; 288, binary_operator:%; 288, 289; 288, 290; 289, identifier:float_fmtstr; 290, identifier:val; 291, if_statement; 291, 292; 291, 299; 292, not_operator; 292, 293; 293, call; 293, 294; 293, 297; 294, attribute; 294, 295; 294, 296; 295, identifier:strval; 296, identifier:startswith; 297, argument_list; 297, 298; 298, string:'0'; 299, block; 299, 300; 299, 309; 300, expression_statement; 300, 301; 301, assignment; 301, 302; 301, 303; 302, identifier:strval; 303, call; 303, 304; 303, 307; 304, attribute; 304, 305; 304, 306; 305, identifier:strval; 306, identifier:rstrip; 307, argument_list; 307, 308; 308, string:'0'; 309, expression_statement; 309, 310; 310, assignment; 310, 311; 310, 312; 311, identifier:strval; 312, call; 312, 313; 312, 316; 313, attribute; 313, 314; 313, 315; 314, identifier:strval; 315, identifier:rstrip; 316, argument_list; 316, 317; 317, string:'.'; 318, expression_statement; 318, 319; 319, assignment; 319, 320; 319, 323; 320, subscript; 320, 321; 320, 322; 321, identifier:statstr_dict; 322, identifier:key; 323, identifier:strval; 324, else_clause; 324, 325; 325, block; 325, 326; 325, 355; 326, if_statement; 326, 327; 326, 334; 326, 346; 327, call; 327, 328; 327, 329; 328, identifier:isinstance; 329, argument_list; 329, 330; 329, 331; 330, identifier:val; 331, attribute; 331, 332; 331, 333; 332, identifier:np; 333, identifier:ndarray; 334, block; 334, 335; 335, expression_statement; 335, 336; 336, assignment; 336, 337; 336, 338; 337, identifier:strval; 338, call; 338, 339; 338, 340; 339, identifier:repr; 340, argument_list; 340, 341; 341, call; 341, 342; 341, 345; 342, attribute; 342, 343; 342, 344; 343, identifier:val; 344, identifier:tolist; 345, argument_list; 346, else_clause; 346, 347; 347, block; 347, 348; 348, expression_statement; 348, 349; 349, assignment; 349, 350; 349, 351; 350, identifier:strval; 351, call; 351, 352; 351, 353; 352, identifier:str; 353, argument_list; 353, 354; 354, identifier:val; 355, expression_statement; 355, 356; 356, assignment; 356, 357; 356, 360; 357, subscript; 357, 358; 357, 359; 358, identifier:statstr_dict; 359, identifier:key; 360, identifier:strval; 361, comment; 362, expression_statement; 362, 363; 363, assignment; 363, 364; 363, 365; 364, identifier:stat_str; 365, call; 365, 366; 365, 367; 366, identifier:repr4; 367, argument_list; 367, 368; 367, 369; 367, 372; 368, identifier:statstr_dict; 369, keyword_argument; 369, 370; 369, 371; 370, identifier:strvals; 371, True; 372, keyword_argument; 372, 373; 372, 374; 373, identifier:newlines; 374, identifier:newlines; 375, comment; 376, if_statement; 376, 377; 376, 380; 377, comparison_operator:is; 377, 378; 377, 379; 378, identifier:lbl; 379, True; 380, block; 380, 381; 380, 393; 381, expression_statement; 381, 382; 382, assignment; 382, 383; 382, 384; 383, identifier:lbl; 384, call; 384, 385; 384, 388; 385, attribute; 385, 386; 385, 387; 386, identifier:ut; 387, identifier:get_varname_from_stack; 388, argument_list; 388, 389; 388, 390; 389, identifier:list_; 390, keyword_argument; 390, 391; 390, 392; 391, identifier:N; 392, integer:1; 393, comment; 394, if_statement; 394, 395; 394, 398; 395, comparison_operator:is; 395, 396; 395, 397; 396, identifier:lbl; 397, None; 398, block; 398, 399; 399, expression_statement; 399, 400; 400, assignment; 400, 401; 400, 402; 401, identifier:stat_str; 402, binary_operator:+; 402, 403; 402, 408; 403, binary_operator:+; 403, 404; 403, 407; 404, binary_operator:+; 404, 405; 404, 406; 405, string:'stats_'; 406, identifier:lbl; 407, string:' = '; 408, identifier:stat_str; 409, if_statement; 409, 410; 409, 411; 410, identifier:align; 411, block; 411, 412; 412, expression_statement; 412, 413; 413, assignment; 413, 414; 413, 415; 414, identifier:stat_str; 415, call; 415, 416; 415, 419; 416, attribute; 416, 417; 416, 418; 417, identifier:ut; 418, identifier:align; 419, argument_list; 419, 420; 419, 421; 420, identifier:stat_str; 421, string:':'; 422, return_statement; 422, 423; 423, identifier:stat_str
def get_stats_str(list_=None, newlines=False, keys=None, exclude_keys=[], lbl=None, precision=None, axis=0, stat_dict=None, use_nan=False, align=False, use_median=False, **kwargs): """ Returns the string version of get_stats DEPRICATE in favor of ut.repr3(ut.get_stats(...)) if keys is not None then it only displays chosen keys excluded keys are always removed CommandLine: python -m utool.util_dev --test-get_stats_str Example: >>> # ENABLE_DOCTEST >>> from utool.util_dev import * # NOQA >>> list_ = [1, 2, 3, 4, 5] >>> newlines = False >>> keys = None >>> exclude_keys = [] >>> lbl = None >>> precision = 2 >>> stat_str = get_stats_str(list_, newlines, keys, exclude_keys, lbl, precision) >>> result = str(stat_str) >>> print(result) {'mean': 3, 'std': 1.41, 'max': 5, 'min': 1, 'nMin': 1, 'nMax': 1, 'shape': (5,)} SeeAlso: repr2 get_stats """ from utool.util_str import repr4 import utool as ut # Get stats dict if stat_dict is None: stat_dict = get_stats(list_, axis=axis, use_nan=use_nan, use_median=use_median) else: stat_dict = stat_dict.copy() # Keep only included keys if specified if keys is not None: for key in list(six.iterkeys(stat_dict)): if key not in keys: del stat_dict[key] # Remove excluded keys for key in exclude_keys: if key in stat_dict: del stat_dict[key] # apply precision statstr_dict = stat_dict.copy() #precisionless_types = (bool,) + six.string_types if precision is not None: assert ut.is_int(precision), 'precision must be an integer' float_fmtstr = '%.' + str(precision) + 'f' for key in list(six.iterkeys(statstr_dict)): val = statstr_dict[key] isfloat = ut.is_float(val) if not isfloat and isinstance(val, list): type_list = list(map(type, val)) if len(type_list) > 0 and ut.allsame(type_list): if ut.is_float(val[0]): isfloat = True val = np.array(val) if isfloat: if isinstance(val, np.ndarray): strval = str([float_fmtstr % v for v in val]).replace('\'', '').lstrip('u') #np.array_str((val), precision=precision) else: strval = float_fmtstr % val if not strval.startswith('0'): strval = strval.rstrip('0') strval = strval.rstrip('.') statstr_dict[key] = strval else: if isinstance(val, np.ndarray): strval = repr(val.tolist()) else: strval = str(val) statstr_dict[key] = strval # format the dictionary string stat_str = repr4(statstr_dict, strvals=True, newlines=newlines) # add a label if requested if lbl is True: lbl = ut.get_varname_from_stack(list_, N=1) # fancy if lbl is not None: stat_str = 'stats_' + lbl + ' = ' + stat_str if align: stat_str = ut.align(stat_str, ':') return stat_str
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 15; 2, function_name:search_module; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 3, 12; 4, identifier:mod; 5, identifier:pat; 6, default_parameter; 6, 7; 6, 8; 7, identifier:ignore_case; 8, True; 9, default_parameter; 9, 10; 9, 11; 10, identifier:recursive; 11, False; 12, default_parameter; 12, 13; 12, 14; 13, identifier:_seen; 14, None; 15, block; 15, 16; 15, 18; 15, 29; 15, 34; 15, 42; 15, 64; 15, 149; 15, 150; 15, 159; 16, expression_statement; 16, 17; 17, comment; 18, if_statement; 18, 19; 18, 26; 19, boolean_operator:and; 19, 20; 19, 23; 20, comparison_operator:is; 20, 21; 20, 22; 21, identifier:_seen; 22, None; 23, comparison_operator:in; 23, 24; 23, 25; 24, identifier:mod; 25, identifier:_seen; 26, block; 26, 27; 27, return_statement; 27, 28; 28, list:[]; 29, import_statement; 29, 30; 30, aliased_import; 30, 31; 30, 33; 31, dotted_name; 31, 32; 32, identifier:utool; 33, identifier:ut; 34, expression_statement; 34, 35; 35, assignment; 35, 36; 35, 37; 36, identifier:reflags; 37, binary_operator:*; 37, 38; 37, 41; 38, attribute; 38, 39; 38, 40; 39, identifier:re; 40, identifier:IGNORECASE; 41, identifier:ignore_case; 42, expression_statement; 42, 43; 43, assignment; 43, 44; 43, 45; 44, identifier:found_list; 45, list_comprehension; 45, 46; 45, 47; 45, 53; 46, identifier:name; 47, for_in_clause; 47, 48; 47, 49; 48, identifier:name; 49, call; 49, 50; 49, 51; 50, identifier:dir; 51, argument_list; 51, 52; 52, identifier:mod; 53, if_clause; 53, 54; 54, call; 54, 55; 54, 58; 55, attribute; 55, 56; 55, 57; 56, identifier:re; 57, identifier:search; 58, argument_list; 58, 59; 58, 60; 58, 61; 59, identifier:pat; 60, identifier:name; 61, keyword_argument; 61, 62; 61, 63; 62, identifier:flags; 63, identifier:reflags; 64, if_statement; 64, 65; 64, 66; 65, identifier:recursive; 66, block; 66, 67; 66, 78; 66, 85; 66, 100; 66, 128; 67, if_statement; 67, 68; 67, 71; 68, comparison_operator:is; 68, 69; 68, 70; 69, identifier:_seen; 70, None; 71, block; 71, 72; 72, expression_statement; 72, 73; 73, assignment; 73, 74; 73, 75; 74, identifier:_seen; 75, call; 75, 76; 75, 77; 76, identifier:set; 77, argument_list; 78, expression_statement; 78, 79; 79, call; 79, 80; 79, 83; 80, attribute; 80, 81; 80, 82; 81, identifier:_seen; 82, identifier:add; 83, argument_list; 83, 84; 84, identifier:mod; 85, expression_statement; 85, 86; 86, assignment; 86, 87; 86, 88; 87, identifier:module_attrs; 88, list_comprehension; 88, 89; 88, 94; 89, call; 89, 90; 89, 91; 90, identifier:getattr; 91, argument_list; 91, 92; 91, 93; 92, identifier:mod; 93, identifier:name; 94, for_in_clause; 94, 95; 94, 96; 95, identifier:name; 96, call; 96, 97; 96, 98; 97, identifier:dir; 98, argument_list; 98, 99; 99, identifier:mod; 100, expression_statement; 100, 101; 101, assignment; 101, 102; 101, 103; 102, identifier:submodules; 103, list_comprehension; 103, 104; 103, 105; 103, 108; 104, identifier:submod; 105, for_in_clause; 105, 106; 105, 107; 106, identifier:submod; 107, identifier:module_attrs; 108, if_clause; 108, 109; 109, boolean_operator:and; 109, 110; 109, 121; 110, boolean_operator:and; 110, 111; 110, 118; 111, call; 111, 112; 111, 113; 112, identifier:isinstance; 113, argument_list; 113, 114; 113, 115; 114, identifier:submod; 115, attribute; 115, 116; 115, 117; 116, identifier:types; 117, identifier:ModuleType; 118, comparison_operator:not; 118, 119; 118, 120; 119, identifier:submod; 120, identifier:_seen; 121, call; 121, 122; 121, 125; 122, attribute; 122, 123; 122, 124; 123, identifier:ut; 124, identifier:is_defined_by_module; 125, argument_list; 125, 126; 125, 127; 126, identifier:submod; 127, identifier:mod; 128, for_statement; 128, 129; 128, 130; 128, 131; 129, identifier:submod; 130, identifier:submodules; 131, block; 131, 132; 132, expression_statement; 132, 133; 133, augmented_assignment:+=; 133, 134; 133, 135; 134, identifier:found_list; 135, call; 135, 136; 135, 137; 136, identifier:search_module; 137, argument_list; 137, 138; 137, 139; 137, 140; 137, 143; 137, 146; 138, identifier:submod; 139, identifier:pat; 140, keyword_argument; 140, 141; 140, 142; 141, identifier:ignore_case; 142, identifier:ignore_case; 143, keyword_argument; 143, 144; 143, 145; 144, identifier:recursive; 145, identifier:recursive; 146, keyword_argument; 146, 147; 146, 148; 147, identifier:_seen; 148, identifier:_seen; 149, comment; 150, expression_statement; 150, 151; 151, assignment; 151, 152; 151, 153; 152, identifier:found_list; 153, call; 153, 154; 153, 157; 154, attribute; 154, 155; 154, 156; 155, identifier:ut; 156, identifier:unique_ordered; 157, argument_list; 157, 158; 158, identifier:found_list; 159, return_statement; 159, 160; 160, identifier:found_list
def search_module(mod, pat, ignore_case=True, recursive=False, _seen=None): r""" Searches module functions, classes, and constants for members matching a pattern. Args: mod (module): live python module pat (str): regular expression Returns: list: found_list CommandLine: python -m utool.util_dev --exec-search_module --mod=utool --pat=module python -m utool.util_dev --exec-search_module --mod=opengm --pat=cut python -m utool.util_dev --exec-search_module --mod=opengm --pat=multi python -m utool.util_dev --exec-search_module --mod=plottool --pat=networkx python -m utool.util_dev --exec-search_module --mod=utool --pat=Levenshtein Example: >>> # ENABLE_DOCTEST >>> from utool.util_dev import * # NOQA >>> import utool as ut >>> recursive = True >>> ignore_case = True >>> modname = ut.get_argval('--mod', type_=str, default='utool') >>> pat = ut.get_argval('--pat', type_=str, default='search') >>> mod = ut.import_modname(modname) >>> print('pat = %r' % (pat,)) >>> print('mod = %r' % (mod,)) >>> found_list = search_module(mod, pat, recursive=recursive) >>> result = ('found_list = %s' % (ut.repr2(found_list),)) >>> print(result) Ignore: mod = cv2 pat = 'freak' """ if _seen is not None and mod in _seen: return [] import utool as ut reflags = re.IGNORECASE * ignore_case found_list = [name for name in dir(mod) if re.search(pat, name, flags=reflags)] if recursive: if _seen is None: _seen = set() _seen.add(mod) module_attrs = [getattr(mod, name) for name in dir(mod)] submodules = [ submod for submod in module_attrs if isinstance(submod, types.ModuleType) and submod not in _seen and ut.is_defined_by_module(submod, mod) ] for submod in submodules: found_list += search_module(submod, pat, ignore_case=ignore_case, recursive=recursive, _seen=_seen) # found_list = [name for name in dir(mod) if name.find(pat) >= 0] found_list = ut.unique_ordered(found_list) return found_list
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 11; 2, function_name:instancelist; 3, parameters; 3, 4; 3, 5; 3, 8; 4, identifier:obj_list; 5, default_parameter; 5, 6; 5, 7; 6, identifier:check; 7, False; 8, default_parameter; 8, 9; 8, 10; 9, identifier:shared_attrs; 10, None; 11, block; 11, 12; 11, 14; 11, 460; 12, expression_statement; 12, 13; 13, comment; 14, class_definition; 14, 15; 14, 16; 14, 18; 15, identifier:InstanceList_; 16, argument_list; 16, 17; 17, identifier:object; 18, block; 18, 19; 18, 217; 18, 254; 18, 288; 18, 315; 18, 330; 18, 371; 18, 403; 18, 438; 19, function_definition; 19, 20; 19, 21; 19, 27; 20, function_name:__init__; 21, parameters; 21, 22; 21, 23; 21, 24; 22, identifier:self; 23, identifier:obj_list; 24, default_parameter; 24, 25; 24, 26; 25, identifier:shared_attrs; 26, None; 27, block; 27, 28; 27, 34; 27, 40; 27, 46; 28, expression_statement; 28, 29; 29, assignment; 29, 30; 29, 33; 30, attribute; 30, 31; 30, 32; 31, identifier:self; 32, identifier:_obj_list; 33, list:[]; 34, expression_statement; 34, 35; 35, assignment; 35, 36; 35, 39; 36, attribute; 36, 37; 36, 38; 37, identifier:self; 38, identifier:_shared_public_attrs; 39, list:[]; 40, expression_statement; 40, 41; 41, assignment; 41, 42; 41, 45; 42, attribute; 42, 43; 42, 44; 43, identifier:self; 44, identifier:_example_type; 45, None; 46, if_statement; 46, 47; 46, 53; 47, comparison_operator:>; 47, 48; 47, 52; 48, call; 48, 49; 48, 50; 49, identifier:len; 50, argument_list; 50, 51; 51, identifier:obj_list; 52, integer:0; 53, block; 53, 54; 53, 59; 53, 65; 53, 71; 53, 78; 53, 84; 53, 128; 53, 129; 53, 133; 53, 155; 54, import_statement; 54, 55; 55, aliased_import; 55, 56; 55, 58; 56, dotted_name; 56, 57; 57, identifier:utool; 58, identifier:ut; 59, expression_statement; 59, 60; 60, assignment; 60, 61; 60, 64; 61, attribute; 61, 62; 61, 63; 62, identifier:self; 63, identifier:_obj_list; 64, identifier:obj_list; 65, expression_statement; 65, 66; 66, assignment; 66, 67; 66, 68; 67, identifier:example_obj; 68, subscript; 68, 69; 68, 70; 69, identifier:obj_list; 70, integer:0; 71, expression_statement; 71, 72; 72, assignment; 72, 73; 72, 74; 73, identifier:example_type; 74, call; 74, 75; 74, 76; 75, identifier:type; 76, argument_list; 76, 77; 77, identifier:example_obj; 78, expression_statement; 78, 79; 79, assignment; 79, 80; 79, 83; 80, attribute; 80, 81; 80, 82; 81, identifier:self; 82, identifier:_example_type; 83, identifier:example_type; 84, if_statement; 84, 85; 84, 88; 85, comparison_operator:is; 85, 86; 85, 87; 86, identifier:shared_attrs; 87, None; 88, block; 88, 89; 89, if_statement; 89, 90; 89, 91; 89, 119; 90, identifier:check; 91, block; 91, 92; 91, 106; 92, expression_statement; 92, 93; 93, assignment; 93, 94; 93, 95; 94, identifier:attrsgen; 95, list_comprehension; 95, 96; 95, 103; 96, call; 96, 97; 96, 98; 97, identifier:set; 98, argument_list; 98, 99; 99, call; 99, 100; 99, 101; 100, identifier:dir; 101, argument_list; 101, 102; 102, identifier:obj; 103, for_in_clause; 103, 104; 103, 105; 104, identifier:obj; 105, identifier:obj_list; 106, expression_statement; 106, 107; 107, assignment; 107, 108; 107, 109; 108, identifier:shared_attrs; 109, call; 109, 110; 109, 111; 110, identifier:list; 111, argument_list; 111, 112; 112, call; 112, 113; 112, 114; 113, identifier:reduce; 114, argument_list; 114, 115; 114, 118; 115, attribute; 115, 116; 115, 117; 116, identifier:set; 117, identifier:intersection; 118, identifier:attrsgen; 119, else_clause; 119, 120; 120, block; 120, 121; 121, expression_statement; 121, 122; 122, assignment; 122, 123; 122, 124; 123, identifier:shared_attrs; 124, call; 124, 125; 124, 126; 125, identifier:dir; 126, argument_list; 126, 127; 127, identifier:example_obj; 128, comment; 129, expression_statement; 129, 130; 130, assignment; 130, 131; 130, 132; 131, identifier:allowed; 132, list:[]; 133, expression_statement; 133, 134; 134, assignment; 134, 135; 134, 138; 135, attribute; 135, 136; 135, 137; 136, identifier:self; 137, identifier:_shared_public_attrs; 138, list_comprehension; 138, 139; 138, 140; 138, 143; 139, identifier:a; 140, for_in_clause; 140, 141; 140, 142; 141, identifier:a; 142, identifier:shared_attrs; 143, if_clause; 143, 144; 144, boolean_operator:or; 144, 145; 144, 148; 145, comparison_operator:in; 145, 146; 145, 147; 146, identifier:a; 147, identifier:allowed; 148, not_operator; 148, 149; 149, call; 149, 150; 149, 153; 150, attribute; 150, 151; 150, 152; 151, identifier:a; 152, identifier:startswith; 153, argument_list; 153, 154; 154, string:'_'; 155, for_statement; 155, 156; 155, 157; 155, 160; 156, identifier:attrname; 157, attribute; 157, 158; 157, 159; 158, identifier:self; 159, identifier:_shared_public_attrs; 160, block; 160, 161; 160, 170; 161, expression_statement; 161, 162; 162, assignment; 162, 163; 162, 164; 163, identifier:attrtype; 164, call; 164, 165; 164, 166; 165, identifier:getattr; 166, argument_list; 166, 167; 166, 168; 166, 169; 167, identifier:example_type; 168, identifier:attrname; 169, None; 170, if_statement; 170, 171; 170, 180; 170, 181; 170, 197; 171, boolean_operator:and; 171, 172; 171, 175; 172, comparison_operator:is; 172, 173; 172, 174; 173, identifier:attrtype; 174, None; 175, call; 175, 176; 175, 177; 176, identifier:isinstance; 177, argument_list; 177, 178; 177, 179; 178, identifier:attrtype; 179, identifier:property; 180, comment; 181, block; 181, 182; 182, expression_statement; 182, 183; 183, call; 183, 184; 183, 185; 184, identifier:setattr; 185, argument_list; 185, 186; 185, 187; 185, 188; 186, identifier:InstanceList_; 187, identifier:attrname; 188, call; 188, 189; 188, 190; 189, identifier:property; 190, argument_list; 190, 191; 191, call; 191, 192; 191, 195; 192, attribute; 192, 193; 192, 194; 193, identifier:self; 194, identifier:_define_prop; 195, argument_list; 195, 196; 196, identifier:attrname; 197, else_clause; 197, 198; 198, block; 198, 199; 198, 208; 199, expression_statement; 199, 200; 200, assignment; 200, 201; 200, 202; 201, identifier:func; 202, call; 202, 203; 202, 206; 203, attribute; 203, 204; 203, 205; 204, identifier:self; 205, identifier:_define_func; 206, argument_list; 206, 207; 207, identifier:attrname; 208, expression_statement; 208, 209; 209, call; 209, 210; 209, 213; 210, attribute; 210, 211; 210, 212; 211, identifier:ut; 212, identifier:inject_func_as_method; 213, argument_list; 213, 214; 213, 215; 213, 216; 214, identifier:self; 215, identifier:func; 216, identifier:attrname; 217, function_definition; 217, 218; 217, 219; 217, 221; 218, function_name:__nice__; 219, parameters; 219, 220; 220, identifier:self; 221, block; 221, 222; 221, 243; 222, if_statement; 222, 223; 222, 228; 222, 233; 223, comparison_operator:is; 223, 224; 223, 227; 224, attribute; 224, 225; 224, 226; 225, identifier:self; 226, identifier:_example_type; 227, None; 228, block; 228, 229; 229, expression_statement; 229, 230; 230, assignment; 230, 231; 230, 232; 231, identifier:typename; 232, string:'object'; 233, else_clause; 233, 234; 234, block; 234, 235; 235, expression_statement; 235, 236; 236, assignment; 236, 237; 236, 238; 237, identifier:typename; 238, attribute; 238, 239; 238, 242; 239, attribute; 239, 240; 239, 241; 240, identifier:self; 241, identifier:_example_type; 242, identifier:__name__; 243, return_statement; 243, 244; 244, binary_operator:%; 244, 245; 244, 246; 245, string:'of %d %s(s)'; 246, tuple; 246, 247; 246, 253; 247, call; 247, 248; 247, 249; 248, identifier:len; 249, argument_list; 249, 250; 250, attribute; 250, 251; 250, 252; 251, identifier:self; 252, identifier:_obj_list; 253, identifier:typename; 254, function_definition; 254, 255; 254, 256; 254, 258; 255, function_name:__repr__; 256, parameters; 256, 257; 257, identifier:self; 258, block; 258, 259; 258, 267; 258, 275; 259, expression_statement; 259, 260; 260, assignment; 260, 261; 260, 262; 261, identifier:classname; 262, attribute; 262, 263; 262, 266; 263, attribute; 263, 264; 263, 265; 264, identifier:self; 265, identifier:__class__; 266, identifier:__name__; 267, expression_statement; 267, 268; 268, assignment; 268, 269; 268, 270; 269, identifier:devnice; 270, call; 270, 271; 270, 274; 271, attribute; 271, 272; 271, 273; 272, identifier:self; 273, identifier:__nice__; 274, argument_list; 275, return_statement; 275, 276; 276, binary_operator:%; 276, 277; 276, 278; 277, string:'<%s(%s) at %s>'; 278, tuple; 278, 279; 278, 280; 278, 281; 279, identifier:classname; 280, identifier:devnice; 281, call; 281, 282; 281, 283; 282, identifier:hex; 283, argument_list; 283, 284; 284, call; 284, 285; 284, 286; 285, identifier:id; 286, argument_list; 286, 287; 287, identifier:self; 288, function_definition; 288, 289; 288, 290; 288, 292; 289, function_name:__str__; 290, parameters; 290, 291; 291, identifier:self; 292, block; 292, 293; 292, 301; 292, 309; 293, expression_statement; 293, 294; 294, assignment; 294, 295; 294, 296; 295, identifier:classname; 296, attribute; 296, 297; 296, 300; 297, attribute; 297, 298; 297, 299; 298, identifier:self; 299, identifier:__class__; 300, identifier:__name__; 301, expression_statement; 301, 302; 302, assignment; 302, 303; 302, 304; 303, identifier:devnice; 304, call; 304, 305; 304, 308; 305, attribute; 305, 306; 305, 307; 306, identifier:self; 307, identifier:__nice__; 308, argument_list; 309, return_statement; 309, 310; 310, binary_operator:%; 310, 311; 310, 312; 311, string:'<%s(%s)>'; 312, tuple; 312, 313; 312, 314; 313, identifier:classname; 314, identifier:devnice; 315, function_definition; 315, 316; 315, 317; 315, 320; 315, 321; 316, function_name:__getitem__; 317, parameters; 317, 318; 317, 319; 318, identifier:self; 319, identifier:key; 320, comment; 321, block; 321, 322; 322, return_statement; 322, 323; 323, call; 323, 324; 323, 327; 324, attribute; 324, 325; 324, 326; 325, identifier:self; 326, identifier:_map_method; 327, argument_list; 327, 328; 327, 329; 328, string:'__getitem__'; 329, identifier:key; 330, function_definition; 330, 331; 330, 332; 330, 335; 331, function_name:_define_func; 332, parameters; 332, 333; 332, 334; 333, identifier:self; 334, identifier:attrname; 335, block; 335, 336; 335, 341; 335, 361; 335, 369; 336, import_statement; 336, 337; 337, aliased_import; 337, 338; 337, 340; 338, dotted_name; 338, 339; 339, identifier:utool; 340, identifier:ut; 341, function_definition; 341, 342; 341, 343; 341, 349; 342, function_name:_wrapper; 343, parameters; 343, 344; 343, 345; 343, 347; 344, identifier:self; 345, list_splat_pattern; 345, 346; 346, identifier:args; 347, dictionary_splat_pattern; 347, 348; 348, identifier:kwargs; 349, block; 349, 350; 350, return_statement; 350, 351; 351, call; 351, 352; 351, 355; 352, attribute; 352, 353; 352, 354; 353, identifier:self; 354, identifier:_map_method; 355, argument_list; 355, 356; 355, 357; 355, 359; 356, identifier:attrname; 357, list_splat; 357, 358; 358, identifier:args; 359, dictionary_splat; 359, 360; 360, identifier:kwargs; 361, expression_statement; 361, 362; 362, call; 362, 363; 362, 366; 363, attribute; 363, 364; 363, 365; 364, identifier:ut; 365, identifier:set_funcname; 366, argument_list; 366, 367; 366, 368; 367, identifier:_wrapper; 368, identifier:attrname; 369, return_statement; 369, 370; 370, identifier:_wrapper; 371, function_definition; 371, 372; 371, 373; 371, 380; 372, function_name:_map_method; 373, parameters; 373, 374; 373, 375; 373, 376; 373, 378; 374, identifier:self; 375, identifier:attrname; 376, list_splat_pattern; 376, 377; 377, identifier:args; 378, dictionary_splat_pattern; 378, 379; 379, identifier:kwargs; 380, block; 380, 381; 380, 401; 381, expression_statement; 381, 382; 382, assignment; 382, 383; 382, 384; 383, identifier:mapped_vals; 384, list_comprehension; 384, 385; 384, 396; 385, call; 385, 386; 385, 391; 386, call; 386, 387; 386, 388; 387, identifier:getattr; 388, argument_list; 388, 389; 388, 390; 389, identifier:obj; 390, identifier:attrname; 391, argument_list; 391, 392; 391, 394; 392, list_splat; 392, 393; 393, identifier:args; 394, dictionary_splat; 394, 395; 395, identifier:kwargs; 396, for_in_clause; 396, 397; 396, 398; 397, identifier:obj; 398, attribute; 398, 399; 398, 400; 399, identifier:self; 400, identifier:_obj_list; 401, return_statement; 401, 402; 402, identifier:mapped_vals; 403, function_definition; 403, 404; 403, 405; 403, 408; 404, function_name:_define_prop; 405, parameters; 405, 406; 405, 407; 406, identifier:self; 407, identifier:attrname; 408, block; 408, 409; 408, 414; 408, 426; 408, 436; 409, import_statement; 409, 410; 410, aliased_import; 410, 411; 410, 413; 411, dotted_name; 411, 412; 412, identifier:utool; 413, identifier:ut; 414, function_definition; 414, 415; 414, 416; 414, 418; 415, function_name:_getter; 416, parameters; 416, 417; 417, identifier:self; 418, block; 418, 419; 419, return_statement; 419, 420; 420, call; 420, 421; 420, 424; 421, attribute; 421, 422; 421, 423; 422, identifier:self; 423, identifier:_map_property; 424, argument_list; 424, 425; 425, identifier:attrname; 426, expression_statement; 426, 427; 427, call; 427, 428; 427, 431; 428, attribute; 428, 429; 428, 430; 429, identifier:ut; 430, identifier:set_funcname; 431, argument_list; 431, 432; 431, 433; 432, identifier:_getter; 433, binary_operator:+; 433, 434; 433, 435; 434, string:'get_'; 435, identifier:attrname; 436, return_statement; 436, 437; 437, identifier:_getter; 438, function_definition; 438, 439; 438, 440; 438, 443; 439, function_name:_map_property; 440, parameters; 440, 441; 440, 442; 441, identifier:self; 442, identifier:attrname; 443, block; 443, 444; 443, 458; 444, expression_statement; 444, 445; 445, assignment; 445, 446; 445, 447; 446, identifier:mapped_vals; 447, list_comprehension; 447, 448; 447, 453; 448, call; 448, 449; 448, 450; 449, identifier:getattr; 450, argument_list; 450, 451; 450, 452; 451, identifier:obj; 452, identifier:attrname; 453, for_in_clause; 453, 454; 453, 455; 454, identifier:obj; 455, attribute; 455, 456; 455, 457; 456, identifier:self; 457, identifier:_obj_list; 458, return_statement; 458, 459; 459, identifier:mapped_vals; 460, return_statement; 460, 461; 461, call; 461, 462; 461, 463; 462, identifier:InstanceList_; 463, argument_list; 463, 464; 463, 465; 464, identifier:obj_list; 465, identifier:shared_attrs
def instancelist(obj_list, check=False, shared_attrs=None): """ Executes methods and attribute calls on a list of objects of the same type Bundles a list of object of the same type into a single object. The new object contains the same functions as each original object but applies them to each element of the list independantly when called. CommandLine: python -m utool.util_dev instancelist Example: >>> # ENABLE_DOCTEST >>> from utool.util_dev import * # NOQA >>> import utool as ut >>> obj_list = ['hi', 'bye', 'foo'] >>> self = ut.instancelist(obj_list, check=False) >>> print(self) >>> print(self.upper()) >>> print(self.isalpha()) """ class InstanceList_(object): def __init__(self, obj_list, shared_attrs=None): self._obj_list = [] self._shared_public_attrs = [] self._example_type = None if len(obj_list) > 0: import utool as ut self._obj_list = obj_list example_obj = obj_list[0] example_type = type(example_obj) self._example_type = example_type if shared_attrs is None: if check: attrsgen = [set(dir(obj)) for obj in obj_list] shared_attrs = list(reduce(set.intersection, attrsgen)) else: shared_attrs = dir(example_obj) #allowed = ['__getitem__'] # TODO, put in metaclass allowed = [] self._shared_public_attrs = [ a for a in shared_attrs if a in allowed or not a.startswith('_') ] for attrname in self._shared_public_attrs: attrtype = getattr(example_type, attrname, None) if attrtype is not None and isinstance(attrtype, property): # need to do this as metaclass setattr(InstanceList_, attrname, property(self._define_prop(attrname))) else: func = self._define_func(attrname) ut.inject_func_as_method(self, func, attrname) def __nice__(self): if self._example_type is None: typename = 'object' else: typename = self._example_type.__name__ return 'of %d %s(s)' % (len(self._obj_list), typename) def __repr__(self): classname = self.__class__.__name__ devnice = self.__nice__() return '<%s(%s) at %s>' % (classname, devnice, hex(id(self))) def __str__(self): classname = self.__class__.__name__ devnice = self.__nice__() return '<%s(%s)>' % (classname, devnice) def __getitem__(self, key): # TODO, put in metaclass return self._map_method('__getitem__', key) def _define_func(self, attrname): import utool as ut def _wrapper(self, *args, **kwargs): return self._map_method(attrname, *args, **kwargs) ut.set_funcname(_wrapper, attrname) return _wrapper def _map_method(self, attrname, *args, **kwargs): mapped_vals = [getattr(obj, attrname)(*args, **kwargs) for obj in self._obj_list] return mapped_vals def _define_prop(self, attrname): import utool as ut def _getter(self): return self._map_property(attrname) ut.set_funcname(_getter, 'get_' + attrname) return _getter def _map_property(self, attrname): mapped_vals = [getattr(obj, attrname) for obj in self._obj_list] return mapped_vals return InstanceList_(obj_list, shared_attrs)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 9; 2, function_name:merge_rows; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:self; 5, identifier:key; 6, default_parameter; 6, 7; 6, 8; 7, identifier:merge_scalars; 8, True; 9, block; 9, 10; 9, 12; 9, 17; 9, 28; 9, 43; 9, 58; 9, 72; 9, 85; 9, 89; 9, 316; 9, 327; 9, 333; 10, expression_statement; 10, 11; 11, comment; 12, import_statement; 12, 13; 13, aliased_import; 13, 14; 13, 16; 14, dotted_name; 14, 15; 15, identifier:utool; 16, identifier:ut; 17, expression_statement; 17, 18; 18, assignment; 18, 19; 18, 22; 19, pattern_list; 19, 20; 19, 21; 20, identifier:unique_labels; 21, identifier:groupxs; 22, call; 22, 23; 22, 26; 23, attribute; 23, 24; 23, 25; 24, identifier:self; 25, identifier:group_indicies; 26, argument_list; 26, 27; 27, identifier:key; 28, expression_statement; 28, 29; 29, assignment; 29, 30; 29, 31; 30, identifier:single_xs; 31, list_comprehension; 31, 32; 31, 33; 31, 36; 32, identifier:xs; 33, for_in_clause; 33, 34; 33, 35; 34, identifier:xs; 35, identifier:groupxs; 36, if_clause; 36, 37; 37, comparison_operator:==; 37, 38; 37, 42; 38, call; 38, 39; 38, 40; 39, identifier:len; 40, argument_list; 40, 41; 41, identifier:xs; 42, integer:1; 43, expression_statement; 43, 44; 44, assignment; 44, 45; 44, 46; 45, identifier:multi_xs; 46, list_comprehension; 46, 47; 46, 48; 46, 51; 47, identifier:xs; 48, for_in_clause; 48, 49; 48, 50; 49, identifier:xs; 50, identifier:groupxs; 51, if_clause; 51, 52; 52, comparison_operator:>; 52, 53; 52, 57; 53, call; 53, 54; 53, 55; 54, identifier:len; 55, argument_list; 55, 56; 56, identifier:xs; 57, integer:1; 58, expression_statement; 58, 59; 59, assignment; 59, 60; 59, 61; 60, identifier:singles; 61, call; 61, 62; 61, 65; 62, attribute; 62, 63; 62, 64; 63, identifier:self; 64, identifier:take; 65, argument_list; 65, 66; 66, call; 66, 67; 66, 70; 67, attribute; 67, 68; 67, 69; 68, identifier:ut; 69, identifier:flatten; 70, argument_list; 70, 71; 71, identifier:single_xs; 72, expression_statement; 72, 73; 73, assignment; 73, 74; 73, 75; 74, identifier:multis; 75, list_comprehension; 75, 76; 75, 82; 76, call; 76, 77; 76, 80; 77, attribute; 77, 78; 77, 79; 78, identifier:self; 79, identifier:take; 80, argument_list; 80, 81; 81, identifier:idxs; 82, for_in_clause; 82, 83; 82, 84; 83, identifier:idxs; 84, identifier:multi_xs; 85, expression_statement; 85, 86; 86, assignment; 86, 87; 86, 88; 87, identifier:merged_groups; 88, list:[]; 89, for_statement; 89, 90; 89, 91; 89, 92; 90, identifier:group; 91, identifier:multis; 92, block; 92, 93; 92, 97; 92, 304; 93, expression_statement; 93, 94; 94, assignment; 94, 95; 94, 96; 95, identifier:newgroup; 96, dictionary; 97, for_statement; 97, 98; 97, 99; 97, 104; 98, identifier:key_; 99, call; 99, 100; 99, 103; 100, attribute; 100, 101; 100, 102; 101, identifier:group; 102, identifier:keys; 103, argument_list; 104, block; 104, 105; 104, 111; 104, 297; 105, expression_statement; 105, 106; 106, assignment; 106, 107; 106, 108; 107, identifier:val; 108, subscript; 108, 109; 108, 110; 109, identifier:group; 110, identifier:key_; 111, if_statement; 111, 112; 111, 115; 111, 116; 111, 123; 111, 148; 111, 173; 111, 194; 111, 216; 112, comparison_operator:==; 112, 113; 112, 114; 113, identifier:key_; 114, identifier:key; 115, comment; 116, block; 116, 117; 117, expression_statement; 117, 118; 118, assignment; 118, 119; 118, 120; 119, identifier:val_; 120, subscript; 120, 121; 120, 122; 121, identifier:val; 122, integer:0; 123, elif_clause; 123, 124; 123, 133; 123, 134; 123, 135; 124, call; 124, 125; 124, 126; 125, identifier:hasattr; 126, argument_list; 126, 127; 126, 132; 127, attribute; 127, 128; 127, 131; 128, subscript; 128, 129; 128, 130; 129, identifier:val; 130, integer:0; 131, identifier:__class__; 132, string:'union'; 133, comment; 134, comment; 135, block; 135, 136; 136, expression_statement; 136, 137; 137, assignment; 137, 138; 137, 139; 138, identifier:val_; 139, call; 139, 140; 139, 145; 140, attribute; 140, 141; 140, 144; 141, attribute; 141, 142; 141, 143; 142, identifier:ut; 143, identifier:oset; 144, identifier:union; 145, argument_list; 145, 146; 146, list_splat; 146, 147; 147, identifier:val; 148, elif_clause; 148, 149; 148, 159; 148, 160; 149, call; 149, 150; 149, 151; 150, identifier:isinstance; 151, argument_list; 151, 152; 151, 155; 152, subscript; 152, 153; 152, 154; 153, identifier:val; 154, integer:0; 155, tuple; 155, 156; 156, attribute; 156, 157; 156, 158; 157, identifier:ut; 158, identifier:oset; 159, comment; 160, block; 160, 161; 161, expression_statement; 161, 162; 162, assignment; 162, 163; 162, 164; 163, identifier:val_; 164, call; 164, 165; 164, 170; 165, attribute; 165, 166; 165, 169; 166, attribute; 166, 167; 166, 168; 167, identifier:ut; 168, identifier:oset; 169, identifier:union; 170, argument_list; 170, 171; 171, list_splat; 171, 172; 172, identifier:val; 173, elif_clause; 173, 174; 173, 182; 173, 183; 174, call; 174, 175; 174, 176; 175, identifier:isinstance; 176, argument_list; 176, 177; 176, 180; 177, subscript; 177, 178; 177, 179; 178, identifier:val; 179, integer:0; 180, parenthesized_expression; 180, 181; 181, identifier:set; 182, comment; 183, block; 183, 184; 184, expression_statement; 184, 185; 185, assignment; 185, 186; 185, 187; 186, identifier:val_; 187, call; 187, 188; 187, 191; 188, attribute; 188, 189; 188, 190; 189, identifier:set; 190, identifier:union; 191, argument_list; 191, 192; 192, list_splat; 192, 193; 193, identifier:val; 194, elif_clause; 194, 195; 194, 204; 194, 205; 195, call; 195, 196; 195, 197; 196, identifier:isinstance; 197, argument_list; 197, 198; 197, 201; 198, subscript; 198, 199; 198, 200; 199, identifier:val; 200, integer:0; 201, tuple; 201, 202; 201, 203; 202, identifier:tuple; 203, identifier:list; 204, comment; 205, block; 205, 206; 205, 215; 206, expression_statement; 206, 207; 207, assignment; 207, 208; 207, 209; 208, identifier:val_; 209, call; 209, 210; 209, 213; 210, attribute; 210, 211; 210, 212; 211, identifier:ut; 212, identifier:flatten; 213, argument_list; 213, 214; 214, identifier:val; 215, comment; 216, else_clause; 216, 217; 217, block; 217, 218; 218, if_statement; 218, 219; 218, 225; 218, 226; 218, 233; 219, call; 219, 220; 219, 223; 220, attribute; 220, 221; 220, 222; 221, identifier:ut; 222, identifier:allsame; 223, argument_list; 223, 224; 224, identifier:val; 225, comment; 226, block; 226, 227; 227, expression_statement; 227, 228; 228, assignment; 228, 229; 228, 230; 229, identifier:val_; 230, subscript; 230, 231; 230, 232; 231, identifier:val; 232, integer:0; 233, else_clause; 233, 234; 234, block; 234, 235; 235, if_statement; 235, 236; 235, 237; 235, 238; 235, 239; 235, 244; 236, identifier:merge_scalars; 237, comment; 238, comment; 239, block; 239, 240; 240, expression_statement; 240, 241; 241, assignment; 241, 242; 241, 243; 242, identifier:val_; 243, identifier:val; 244, else_clause; 244, 245; 245, block; 245, 246; 246, if_statement; 246, 247; 246, 248; 246, 249; 246, 284; 247, True; 248, comment; 249, block; 249, 250; 249, 259; 250, expression_statement; 250, 251; 251, assignment; 251, 252; 251, 253; 252, identifier:other_vals; 253, call; 253, 254; 253, 257; 254, attribute; 254, 255; 254, 256; 255, identifier:ut; 256, identifier:filter_Nones; 257, argument_list; 257, 258; 258, identifier:val; 259, if_statement; 259, 260; 259, 266; 259, 273; 260, comparison_operator:==; 260, 261; 260, 265; 261, call; 261, 262; 261, 263; 262, identifier:len; 263, argument_list; 263, 264; 264, identifier:other_vals; 265, integer:1; 266, block; 266, 267; 267, expression_statement; 267, 268; 268, assignment; 268, 269; 268, 270; 269, identifier:val_; 270, subscript; 270, 271; 270, 272; 271, identifier:val; 272, integer:0; 273, else_clause; 273, 274; 274, block; 274, 275; 275, raise_statement; 275, 276; 276, call; 276, 277; 276, 278; 277, identifier:ValueError; 278, argument_list; 278, 279; 279, binary_operator:%; 279, 280; 279, 281; 280, string:'tried to merge a scalar in %r, val=%r'; 281, tuple; 281, 282; 281, 283; 282, identifier:key_; 283, identifier:val; 284, else_clause; 284, 285; 284, 286; 284, 287; 285, comment; 286, comment; 287, block; 287, 288; 288, raise_statement; 288, 289; 289, call; 289, 290; 289, 291; 290, identifier:ValueError; 291, argument_list; 291, 292; 292, binary_operator:%; 292, 293; 292, 294; 293, string:'tried to merge a scalar in %r, val=%r'; 294, tuple; 294, 295; 294, 296; 295, identifier:key_; 296, identifier:val; 297, expression_statement; 297, 298; 298, assignment; 298, 299; 298, 302; 299, subscript; 299, 300; 299, 301; 300, identifier:newgroup; 301, identifier:key_; 302, list:[val_]; 302, 303; 303, identifier:val_; 304, expression_statement; 304, 305; 305, call; 305, 306; 305, 309; 306, attribute; 306, 307; 306, 308; 307, identifier:merged_groups; 308, identifier:append; 309, argument_list; 309, 310; 310, call; 310, 311; 310, 314; 311, attribute; 311, 312; 311, 313; 312, identifier:ut; 313, identifier:ColumnLists; 314, argument_list; 314, 315; 315, identifier:newgroup; 316, expression_statement; 316, 317; 317, assignment; 317, 318; 317, 319; 318, identifier:merged_multi; 319, call; 319, 320; 319, 325; 320, attribute; 320, 321; 320, 324; 321, attribute; 321, 322; 321, 323; 322, identifier:self; 323, identifier:__class__; 324, identifier:flatten; 325, argument_list; 325, 326; 326, identifier:merged_groups; 327, expression_statement; 327, 328; 328, assignment; 328, 329; 328, 330; 329, identifier:merged; 330, binary_operator:+; 330, 331; 330, 332; 331, identifier:singles; 332, identifier:merged_multi; 333, return_statement; 333, 334; 334, identifier:merged
def merge_rows(self, key, merge_scalars=True): """ Uses key as a unique index an merges all duplicates rows. Use cast_column to modify types of columns before merging to affect behavior of duplicate rectification. Args: key: row to merge on merge_scalars: if True, scalar values become lists Example: >>> # DISABLE_DOCTEST >>> from utool.util_dev import * # NOQA >>> import utool as ut >>> key_to_list = { >>> 'uuid': [1, 1, 2, 3, 4, 2, 1], >>> 'a': [1, 2, 3, 4, 5, 6, 7], >>> 'b': [[1], [2], [3], [4], [5], [6], [7]], >>> 'c': [[1], [1], [2], [3], [4], [2], [1]], >>> } >>> self = ColumnLists(key_to_list) >>> key = 'uuid' >>> newself = self.merge_rows('uuid') >>> print(newself.to_csv()) # a, c, b, uuid 4, [3], [4], 3 5, [4], [5], 4 "[1, 2, 7]", "[1, 1, 1]", "[1, 2, 7]", "[1, 1, 1]" "[3, 6]", "[2, 2]", "[3, 6]", "[2, 2]" """ import utool as ut unique_labels, groupxs = self.group_indicies(key) single_xs = [xs for xs in groupxs if len(xs) == 1] multi_xs = [xs for xs in groupxs if len(xs) > 1] singles = self.take(ut.flatten(single_xs)) multis = [self.take(idxs) for idxs in multi_xs] merged_groups = [] for group in multis: newgroup = {} for key_ in group.keys(): val = group[key_] if key_ == key: # key_ was garuenteed unique val_ = val[0] elif hasattr(val[0].__class__, 'union'): # HACK # Sets are unioned val_ = ut.oset.union(*val) elif isinstance(val[0], (ut.oset,)): # Sets are unioned val_ = ut.oset.union(*val) elif isinstance(val[0], (set)): # Sets are unioned val_ = set.union(*val) elif isinstance(val[0], (tuple, list)): # Lists are merged together val_ = ut.flatten(val) #val_ = ut.unique(ut.flatten(val)) else: if ut.allsame(val): # Merge items that are the same val_ = val[0] else: if merge_scalars: # If mergeing scalars is ok, then # Values become lists if they are different val_ = val else: if True: # If there is only one non-none value then use that. other_vals = ut.filter_Nones(val) if len(other_vals) == 1: val_ = val[0] else: raise ValueError( 'tried to merge a scalar in %r, val=%r' % ( key_, val)) else: # If merging scalars is not ok, then # we must raise an error raise ValueError( 'tried to merge a scalar in %r, val=%r' % ( key_, val)) newgroup[key_] = [val_] merged_groups.append(ut.ColumnLists(newgroup)) merged_multi = self.__class__.flatten(merged_groups) merged = singles + merged_multi return merged
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:_inject_execstr; 3, parameters; 3, 4; 3, 5; 4, identifier:modname; 5, identifier:import_tuples; 6, block; 6, 7; 6, 9; 6, 34; 6, 43; 6, 53; 6, 63; 6, 67; 6, 71; 6, 114; 6, 131; 6, 147; 6, 161; 7, expression_statement; 7, 8; 8, comment; 9, if_statement; 9, 10; 9, 13; 9, 14; 9, 23; 10, comparison_operator:==; 10, 11; 10, 12; 11, identifier:modname; 12, string:'utool'; 13, comment; 14, block; 14, 15; 14, 19; 15, expression_statement; 15, 16; 16, assignment; 16, 17; 16, 18; 17, identifier:injecter; 18, string:'util_inject'; 19, expression_statement; 19, 20; 20, assignment; 20, 21; 20, 22; 21, identifier:injecter_import; 22, string:''; 23, else_clause; 23, 24; 23, 25; 24, comment; 25, block; 25, 26; 25, 30; 26, expression_statement; 26, 27; 27, assignment; 27, 28; 27, 29; 28, identifier:injecter_import; 29, string:'import utool'; 30, expression_statement; 30, 31; 31, assignment; 31, 32; 31, 33; 32, identifier:injecter; 33, string:'utool'; 34, expression_statement; 34, 35; 35, assignment; 35, 36; 35, 37; 36, identifier:injectstr_fmt; 37, call; 37, 38; 37, 41; 38, attribute; 38, 39; 38, 40; 39, identifier:textwrap; 40, identifier:dedent; 41, argument_list; 41, 42; 42, comment; 43, expression_statement; 43, 44; 44, assignment; 44, 45; 44, 46; 45, identifier:injectstr_fmt; 46, call; 46, 47; 46, 50; 47, attribute; 47, 48; 47, 49; 48, identifier:injectstr_fmt; 49, identifier:replace; 50, argument_list; 50, 51; 50, 52; 51, string:'# STARTBLOCK'; 52, string:''; 53, expression_statement; 53, 54; 54, assignment; 54, 55; 54, 56; 55, identifier:injectstr_fmt; 56, call; 56, 57; 56, 60; 57, attribute; 57, 58; 57, 59; 58, identifier:injectstr_fmt; 59, identifier:replace; 60, argument_list; 60, 61; 60, 62; 61, string:'# ENDBLOCK'; 62, string:''; 63, expression_statement; 63, 64; 64, assignment; 64, 65; 64, 66; 65, identifier:rrrdir_fmt; 66, string:' get_reload_subs({modname})(verbose=verbose)'; 67, expression_statement; 67, 68; 68, assignment; 68, 69; 68, 70; 69, identifier:rrrfile_fmt; 70, string:' get_rrr({modname})(verbose > 1)'; 71, function_definition; 71, 72; 71, 73; 71, 75; 72, function_name:_reload_command; 73, parameters; 73, 74; 74, identifier:tup; 75, block; 75, 76; 76, if_statement; 76, 77; 76, 89; 76, 101; 77, boolean_operator:and; 77, 78; 77, 84; 78, comparison_operator:>; 78, 79; 78, 83; 79, call; 79, 80; 79, 81; 80, identifier:len; 81, argument_list; 81, 82; 82, identifier:tup; 83, integer:2; 84, comparison_operator:is; 84, 85; 84, 88; 85, subscript; 85, 86; 85, 87; 86, identifier:tup; 87, integer:2; 88, True; 89, block; 89, 90; 90, return_statement; 90, 91; 91, call; 91, 92; 91, 95; 92, attribute; 92, 93; 92, 94; 93, identifier:rrrdir_fmt; 94, identifier:format; 95, argument_list; 95, 96; 96, keyword_argument; 96, 97; 96, 98; 97, identifier:modname; 98, subscript; 98, 99; 98, 100; 99, identifier:tup; 100, integer:0; 101, else_clause; 101, 102; 102, block; 102, 103; 103, return_statement; 103, 104; 104, call; 104, 105; 104, 108; 105, attribute; 105, 106; 105, 107; 106, identifier:rrrfile_fmt; 107, identifier:format; 108, argument_list; 108, 109; 109, keyword_argument; 109, 110; 109, 111; 110, identifier:modname; 111, subscript; 111, 112; 111, 113; 112, identifier:tup; 113, integer:0; 114, expression_statement; 114, 115; 115, assignment; 115, 116; 115, 117; 116, identifier:reload_body; 117, call; 117, 118; 117, 130; 118, attribute; 118, 119; 118, 129; 119, call; 119, 120; 119, 123; 120, attribute; 120, 121; 120, 122; 121, string:'\n'; 122, identifier:join; 123, argument_list; 123, 124; 124, call; 124, 125; 124, 126; 125, identifier:map; 126, argument_list; 126, 127; 126, 128; 127, identifier:_reload_command; 128, identifier:import_tuples; 129, identifier:strip; 130, argument_list; 131, expression_statement; 131, 132; 132, assignment; 132, 133; 132, 134; 133, identifier:format_dict; 134, dictionary; 134, 135; 134, 138; 134, 141; 134, 144; 135, pair; 135, 136; 135, 137; 136, string:'modname'; 137, identifier:modname; 138, pair; 138, 139; 138, 140; 139, string:'reload_body'; 140, identifier:reload_body; 141, pair; 141, 142; 141, 143; 142, string:'injecter'; 143, identifier:injecter; 144, pair; 144, 145; 144, 146; 145, string:'injecter_import'; 146, identifier:injecter_import; 147, expression_statement; 147, 148; 148, assignment; 148, 149; 148, 150; 149, identifier:inject_execstr; 150, call; 150, 151; 150, 160; 151, attribute; 151, 152; 151, 159; 152, call; 152, 153; 152, 156; 153, attribute; 153, 154; 153, 155; 154, identifier:injectstr_fmt; 155, identifier:format; 156, argument_list; 156, 157; 157, dictionary_splat; 157, 158; 158, identifier:format_dict; 159, identifier:strip; 160, argument_list; 161, return_statement; 161, 162; 162, identifier:inject_execstr
def _inject_execstr(modname, import_tuples): """ Injection and Reload String Defs """ if modname == 'utool': # Special case import of the util_inject module injecter = 'util_inject' injecter_import = '' else: # Normal case implicit import of util_inject injecter_import = 'import utool' injecter = 'utool' injectstr_fmt = textwrap.dedent( r''' # STARTBLOCK {injecter_import} print, rrr, profile = {injecter}.inject2(__name__, '[{modname}]') def reassign_submodule_attributes(verbose=1): """ Updates attributes in the __init__ modules with updated attributes in the submodules. """ import sys if verbose and '--quiet' not in sys.argv: print('dev reimport') # Self import import {modname} # Implicit reassignment. seen_ = set([]) for tup in IMPORT_TUPLES: if len(tup) > 2 and tup[2]: continue # dont import package names submodname, fromimports = tup[0:2] submod = getattr({modname}, submodname) for attr in dir(submod): if attr.startswith('_'): continue if attr in seen_: # This just holds off bad behavior # but it does mimic normal util_import behavior # which is good continue seen_.add(attr) setattr({modname}, attr, getattr(submod, attr)) def reload_subs(verbose=1): """ Reloads {modname} and submodules """ if verbose: print('Reloading {modname} submodules') rrr(verbose > 1) def wrap_fbrrr(mod): def fbrrr(*args, **kwargs): """ fallback reload """ if verbose > 0: print('Auto-reload (using rrr) not setup for mod=%r' % (mod,)) return fbrrr def get_rrr(mod): if hasattr(mod, 'rrr'): return mod.rrr else: return wrap_fbrrr(mod) def get_reload_subs(mod): return getattr(mod, 'reload_subs', wrap_fbrrr(mod)) {reload_body} rrr(verbose > 1) try: # hackish way of propogating up the new reloaded submodule attributes reassign_submodule_attributes(verbose=verbose) except Exception as ex: print(ex) rrrr = reload_subs # ENDBLOCK ''') injectstr_fmt = injectstr_fmt.replace('# STARTBLOCK', '') injectstr_fmt = injectstr_fmt.replace('# ENDBLOCK', '') rrrdir_fmt = ' get_reload_subs({modname})(verbose=verbose)' rrrfile_fmt = ' get_rrr({modname})(verbose > 1)' def _reload_command(tup): if len(tup) > 2 and tup[2] is True: return rrrdir_fmt.format(modname=tup[0]) else: return rrrfile_fmt.format(modname=tup[0]) reload_body = '\n'.join(map(_reload_command, import_tuples)).strip() format_dict = { 'modname': modname, 'reload_body': reload_body, 'injecter': injecter, 'injecter_import': injecter_import, } inject_execstr = injectstr_fmt.format(**format_dict).strip() return inject_execstr
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 33; 2, function_name:dynamic_import; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 3, 12; 3, 15; 3, 18; 3, 21; 3, 24; 3, 27; 3, 30; 4, identifier:modname; 5, identifier:import_tuples; 6, default_parameter; 6, 7; 6, 8; 7, identifier:developing; 8, True; 9, default_parameter; 9, 10; 9, 11; 10, identifier:ignore_froms; 11, list:[]; 12, default_parameter; 12, 13; 12, 14; 13, identifier:dump; 14, False; 15, default_parameter; 15, 16; 15, 17; 16, identifier:ignore_startswith; 17, list:[]; 18, default_parameter; 18, 19; 18, 20; 19, identifier:ignore_endswith; 20, list:[]; 21, default_parameter; 21, 22; 21, 23; 22, identifier:ignore_list; 23, list:[]; 24, default_parameter; 24, 25; 24, 26; 25, identifier:check_not_imported; 26, True; 27, default_parameter; 27, 28; 27, 29; 28, identifier:return_initstr; 29, False; 30, default_parameter; 30, 31; 30, 32; 31, identifier:verbose; 32, False; 33, block; 33, 34; 33, 36; 33, 46; 33, 47; 33, 66; 33, 67; 33, 77; 33, 78; 33, 88; 33, 89; 33, 130; 33, 138; 33, 139; 33, 162; 33, 173; 33, 183; 33, 226; 33, 227; 33, 454; 34, expression_statement; 34, 35; 35, comment; 36, if_statement; 36, 37; 36, 38; 37, identifier:verbose; 38, block; 38, 39; 39, expression_statement; 39, 40; 40, call; 40, 41; 40, 42; 41, identifier:print; 42, argument_list; 42, 43; 43, binary_operator:%; 43, 44; 43, 45; 44, string:'[UTIL_IMPORT] Running Dynamic Imports for modname=%r '; 45, identifier:modname; 46, comment; 47, try_statement; 47, 48; 47, 57; 48, block; 48, 49; 49, expression_statement; 49, 50; 50, assignment; 50, 51; 50, 52; 51, identifier:module; 52, subscript; 52, 53; 52, 56; 53, attribute; 53, 54; 53, 55; 54, identifier:sys; 55, identifier:modules; 56, identifier:modname; 57, except_clause; 57, 58; 58, block; 58, 59; 59, expression_statement; 59, 60; 60, assignment; 60, 61; 60, 62; 61, identifier:module; 62, call; 62, 63; 62, 64; 63, identifier:__import__; 64, argument_list; 64, 65; 65, identifier:modname; 66, comment; 67, expression_statement; 67, 68; 68, assignment; 68, 69; 68, 70; 69, identifier:imports; 70, list_comprehension; 70, 71; 70, 74; 71, subscript; 71, 72; 71, 73; 72, identifier:tup; 73, integer:0; 74, for_in_clause; 74, 75; 74, 76; 75, identifier:tup; 76, identifier:import_tuples; 77, comment; 78, expression_statement; 78, 79; 79, call; 79, 80; 79, 81; 80, identifier:__excecute_imports; 81, argument_list; 81, 82; 81, 83; 81, 84; 81, 85; 82, identifier:module; 83, identifier:modname; 84, identifier:imports; 85, keyword_argument; 85, 86; 85, 87; 86, identifier:verbose; 87, identifier:verbose; 88, comment; 89, if_statement; 89, 90; 89, 91; 89, 116; 90, identifier:developing; 91, block; 91, 92; 92, expression_statement; 92, 93; 93, assignment; 93, 94; 93, 95; 94, identifier:from_imports; 95, call; 95, 96; 95, 97; 96, identifier:__execute_fromimport_star; 97, argument_list; 97, 98; 97, 99; 97, 100; 97, 101; 97, 104; 97, 107; 97, 110; 97, 113; 98, identifier:module; 99, identifier:modname; 100, identifier:import_tuples; 101, keyword_argument; 101, 102; 101, 103; 102, identifier:ignore_list; 103, identifier:ignore_list; 104, keyword_argument; 104, 105; 104, 106; 105, identifier:ignore_startswith; 106, identifier:ignore_startswith; 107, keyword_argument; 107, 108; 107, 109; 108, identifier:ignore_endswith; 109, identifier:ignore_endswith; 110, keyword_argument; 110, 111; 110, 112; 111, identifier:check_not_imported; 112, identifier:check_not_imported; 113, keyword_argument; 113, 114; 113, 115; 114, identifier:verbose; 115, identifier:verbose; 116, else_clause; 116, 117; 117, block; 117, 118; 118, expression_statement; 118, 119; 119, assignment; 119, 120; 119, 121; 120, identifier:from_imports; 121, call; 121, 122; 121, 123; 122, identifier:__execute_fromimport; 123, argument_list; 123, 124; 123, 125; 123, 126; 123, 127; 124, identifier:module; 125, identifier:modname; 126, identifier:import_tuples; 127, keyword_argument; 127, 128; 127, 129; 128, identifier:verbose; 129, identifier:verbose; 130, expression_statement; 130, 131; 131, assignment; 131, 132; 131, 133; 132, identifier:inject_execstr; 133, call; 133, 134; 133, 135; 134, identifier:_inject_execstr; 135, argument_list; 135, 136; 135, 137; 136, identifier:modname; 137, identifier:import_tuples; 138, comment; 139, expression_statement; 139, 140; 140, assignment; 140, 141; 140, 142; 141, identifier:dump_requested; 142, boolean_operator:or; 142, 143; 142, 161; 143, parenthesized_expression; 143, 144; 144, boolean_operator:or; 144, 145; 144, 153; 145, comparison_operator:in; 145, 146; 145, 150; 146, parenthesized_expression; 146, 147; 147, binary_operator:%; 147, 148; 147, 149; 148, string:'--dump-%s-init'; 149, identifier:modname; 150, attribute; 150, 151; 150, 152; 151, identifier:sys; 152, identifier:argv; 153, comparison_operator:in; 153, 154; 153, 158; 154, parenthesized_expression; 154, 155; 155, binary_operator:%; 155, 156; 155, 157; 156, string:'--print-%s-init'; 157, identifier:modname; 158, attribute; 158, 159; 158, 160; 159, identifier:sys; 160, identifier:argv; 161, identifier:dump; 162, expression_statement; 162, 163; 163, assignment; 163, 164; 163, 165; 164, identifier:overwrite_requested; 165, comparison_operator:in; 165, 166; 165, 170; 166, parenthesized_expression; 166, 167; 167, binary_operator:%; 167, 168; 167, 169; 168, string:'--update-%s-init'; 169, identifier:modname; 170, attribute; 170, 171; 170, 172; 171, identifier:sys; 172, identifier:argv; 173, if_statement; 173, 174; 173, 175; 174, identifier:verbose; 175, block; 175, 176; 176, expression_statement; 176, 177; 177, call; 177, 178; 177, 179; 178, identifier:print; 179, argument_list; 179, 180; 180, binary_operator:%; 180, 181; 180, 182; 181, string:'[UTIL_IMPORT] Finished Dynamic Imports for modname=%r '; 182, identifier:modname; 183, if_statement; 183, 184; 183, 185; 184, identifier:dump_requested; 185, block; 185, 186; 185, 198; 186, expression_statement; 186, 187; 187, assignment; 187, 188; 187, 189; 188, identifier:is_main_proc; 189, comparison_operator:==; 189, 190; 189, 197; 190, attribute; 190, 191; 190, 196; 191, call; 191, 192; 191, 195; 192, attribute; 192, 193; 192, 194; 193, identifier:multiprocessing; 194, identifier:current_process; 195, argument_list; 196, identifier:name; 197, string:'MainProcess'; 198, if_statement; 198, 199; 198, 200; 199, identifier:is_main_proc; 200, block; 200, 201; 200, 206; 200, 216; 201, import_from_statement; 201, 202; 201, 204; 202, dotted_name; 202, 203; 203, identifier:utool; 204, dotted_name; 204, 205; 205, identifier:util_str; 206, expression_statement; 206, 207; 207, assignment; 207, 208; 207, 209; 208, identifier:initstr; 209, call; 209, 210; 209, 211; 210, identifier:_initstr; 211, argument_list; 211, 212; 211, 213; 211, 214; 211, 215; 212, identifier:modname; 213, identifier:imports; 214, identifier:from_imports; 215, identifier:inject_execstr; 216, expression_statement; 216, 217; 217, call; 217, 218; 217, 219; 218, identifier:print; 219, argument_list; 219, 220; 220, call; 220, 221; 220, 224; 221, attribute; 221, 222; 221, 223; 222, identifier:util_str; 223, identifier:indent; 224, argument_list; 224, 225; 225, identifier:initstr; 226, comment; 227, if_statement; 227, 228; 227, 229; 228, identifier:overwrite_requested; 229, block; 229, 230; 229, 232; 229, 244; 230, expression_statement; 230, 231; 231, comment; 232, expression_statement; 232, 233; 233, assignment; 233, 234; 233, 235; 234, identifier:is_main_proc; 235, comparison_operator:==; 235, 236; 235, 243; 236, attribute; 236, 237; 236, 242; 237, call; 237, 238; 237, 241; 238, attribute; 238, 239; 238, 240; 239, identifier:multiprocessing; 240, identifier:current_process; 241, argument_list; 242, identifier:name; 243, string:'MainProcess'; 244, if_statement; 244, 245; 244, 246; 245, identifier:is_main_proc; 246, block; 246, 247; 246, 252; 246, 260; 246, 273; 246, 282; 246, 283; 246, 284; 246, 296; 246, 303; 246, 308; 246, 312; 246, 316; 246, 320; 246, 321; 246, 322; 246, 405; 246, 406; 246, 407; 247, import_from_statement; 247, 248; 247, 250; 248, dotted_name; 248, 249; 249, identifier:utool; 250, dotted_name; 250, 251; 251, identifier:util_str; 252, import_from_statement; 252, 253; 252, 256; 252, 258; 253, dotted_name; 253, 254; 253, 255; 254, identifier:os; 255, identifier:path; 256, dotted_name; 256, 257; 257, identifier:join; 258, dotted_name; 258, 259; 259, identifier:exists; 260, expression_statement; 260, 261; 261, assignment; 261, 262; 261, 263; 262, identifier:initstr; 263, call; 263, 264; 263, 265; 264, identifier:_initstr; 265, argument_list; 265, 266; 265, 267; 265, 268; 265, 269; 265, 270; 266, identifier:modname; 267, identifier:imports; 268, identifier:from_imports; 269, identifier:inject_execstr; 270, keyword_argument; 270, 271; 270, 272; 271, identifier:withheader; 272, False; 273, expression_statement; 273, 274; 274, assignment; 274, 275; 274, 276; 275, identifier:new_else; 276, call; 276, 277; 276, 280; 277, attribute; 277, 278; 277, 279; 278, identifier:util_str; 279, identifier:indent; 280, argument_list; 280, 281; 281, identifier:initstr; 282, comment; 283, comment; 284, expression_statement; 284, 285; 285, assignment; 285, 286; 285, 287; 286, identifier:init_fpath; 287, call; 287, 288; 287, 289; 288, identifier:join; 289, argument_list; 289, 290; 289, 295; 290, subscript; 290, 291; 290, 294; 291, attribute; 291, 292; 291, 293; 292, identifier:module; 293, identifier:__path__; 294, integer:0; 295, string:'__init__.py'; 296, expression_statement; 296, 297; 297, call; 297, 298; 297, 299; 298, identifier:print; 299, argument_list; 299, 300; 300, binary_operator:%; 300, 301; 300, 302; 301, string:'attempting to update: %r'; 302, identifier:init_fpath; 303, assert_statement; 303, 304; 304, call; 304, 305; 304, 306; 305, identifier:exists; 306, argument_list; 306, 307; 307, identifier:init_fpath; 308, expression_statement; 308, 309; 309, assignment; 309, 310; 309, 311; 310, identifier:new_lines; 311, list:[]; 312, expression_statement; 312, 313; 313, assignment; 313, 314; 313, 315; 314, identifier:editing; 315, False; 316, expression_statement; 316, 317; 317, assignment; 317, 318; 317, 319; 318, identifier:updated; 319, False; 320, comment; 321, comment; 322, with_statement; 322, 323; 322, 333; 322, 334; 323, with_clause; 323, 324; 324, with_item; 324, 325; 325, as_pattern; 325, 326; 325, 331; 326, call; 326, 327; 326, 328; 327, identifier:open; 328, argument_list; 328, 329; 328, 330; 329, identifier:init_fpath; 330, string:'r'; 331, as_pattern_target; 331, 332; 332, identifier:file_; 333, comment; 334, block; 334, 335; 334, 343; 335, expression_statement; 335, 336; 336, assignment; 336, 337; 336, 338; 337, identifier:lines; 338, call; 338, 339; 338, 342; 339, attribute; 339, 340; 339, 341; 340, identifier:file_; 341, identifier:readlines; 342, argument_list; 343, for_statement; 343, 344; 343, 345; 343, 346; 344, identifier:line; 345, identifier:lines; 346, block; 346, 347; 346, 358; 346, 389; 347, if_statement; 347, 348; 347, 350; 348, not_operator; 348, 349; 349, identifier:editing; 350, block; 350, 351; 351, expression_statement; 351, 352; 352, call; 352, 353; 352, 356; 353, attribute; 353, 354; 353, 355; 354, identifier:new_lines; 355, identifier:append; 356, argument_list; 356, 357; 357, identifier:line; 358, if_statement; 358, 359; 358, 369; 359, call; 359, 360; 359, 367; 360, attribute; 360, 361; 360, 366; 361, call; 361, 362; 361, 365; 362, attribute; 362, 363; 362, 364; 363, identifier:line; 364, identifier:strip; 365, argument_list; 366, identifier:startswith; 367, argument_list; 367, 368; 368, string:'# <AUTOGEN_INIT>'; 369, block; 369, 370; 369, 381; 369, 385; 370, expression_statement; 370, 371; 371, call; 371, 372; 371, 375; 372, attribute; 372, 373; 372, 374; 373, identifier:new_lines; 374, identifier:append; 375, argument_list; 375, 376; 376, binary_operator:+; 376, 377; 376, 380; 377, binary_operator:+; 377, 378; 377, 379; 378, string:'\n'; 379, identifier:new_else; 380, string:'\n # </AUTOGEN_INIT>\n'; 381, expression_statement; 381, 382; 382, assignment; 382, 383; 382, 384; 383, identifier:editing; 384, True; 385, expression_statement; 385, 386; 386, assignment; 386, 387; 386, 388; 387, identifier:updated; 388, True; 389, if_statement; 389, 390; 389, 400; 390, call; 390, 391; 390, 398; 391, attribute; 391, 392; 391, 397; 392, call; 392, 393; 392, 396; 393, attribute; 393, 394; 393, 395; 394, identifier:line; 395, identifier:strip; 396, argument_list; 397, identifier:startswith; 398, argument_list; 398, 399; 399, string:'# </AUTOGEN_INIT>'; 400, block; 400, 401; 401, expression_statement; 401, 402; 402, assignment; 402, 403; 402, 404; 403, identifier:editing; 404, False; 405, comment; 406, comment; 407, if_statement; 407, 408; 407, 409; 407, 445; 408, identifier:updated; 409, block; 409, 410; 409, 417; 409, 426; 410, expression_statement; 410, 411; 411, call; 411, 412; 411, 413; 412, identifier:print; 413, argument_list; 413, 414; 414, binary_operator:%; 414, 415; 414, 416; 415, string:'writing updated file: %r'; 416, identifier:init_fpath; 417, expression_statement; 417, 418; 418, assignment; 418, 419; 418, 420; 419, identifier:new_text; 420, call; 420, 421; 420, 424; 421, attribute; 421, 422; 421, 423; 422, string:''; 423, identifier:join; 424, argument_list; 424, 425; 425, identifier:new_lines; 426, with_statement; 426, 427; 426, 437; 427, with_clause; 427, 428; 428, with_item; 428, 429; 429, as_pattern; 429, 430; 429, 435; 430, call; 430, 431; 430, 432; 431, identifier:open; 432, argument_list; 432, 433; 432, 434; 433, identifier:init_fpath; 434, string:'w'; 435, as_pattern_target; 435, 436; 436, identifier:file_; 437, block; 437, 438; 438, expression_statement; 438, 439; 439, call; 439, 440; 439, 443; 440, attribute; 440, 441; 440, 442; 441, identifier:file_; 442, identifier:write; 443, argument_list; 443, 444; 444, identifier:new_text; 445, else_clause; 445, 446; 446, block; 446, 447; 447, expression_statement; 447, 448; 448, call; 448, 449; 448, 450; 449, identifier:print; 450, argument_list; 450, 451; 451, binary_operator:%; 451, 452; 451, 453; 452, string:'no write hook for file: %r'; 453, identifier:init_fpath; 454, if_statement; 454, 455; 454, 456; 454, 474; 455, identifier:return_initstr; 456, block; 456, 457; 456, 470; 457, expression_statement; 457, 458; 458, assignment; 458, 459; 458, 460; 459, identifier:initstr; 460, call; 460, 461; 460, 462; 461, identifier:_initstr; 462, argument_list; 462, 463; 462, 464; 462, 465; 462, 466; 462, 467; 463, identifier:modname; 464, identifier:imports; 465, identifier:from_imports; 466, string:''; 467, keyword_argument; 467, 468; 467, 469; 468, identifier:withheader; 469, False; 470, return_statement; 470, 471; 471, expression_list; 471, 472; 471, 473; 472, identifier:inject_execstr; 473, identifier:initstr; 474, else_clause; 474, 475; 475, block; 475, 476; 476, return_statement; 476, 477; 477, identifier:inject_execstr
def dynamic_import(modname, import_tuples, developing=True, ignore_froms=[], dump=False, ignore_startswith=[], ignore_endswith=[], ignore_list=[], check_not_imported=True, return_initstr=False, verbose=False): """ MAIN ENTRY POINT Dynamically import listed util libraries and their attributes. Create reload_subs function. Using __import__ like this is typically not considered good style However, it is better than import * and this will generate the good file text that can be used when the module is 'frozen" Returns: str: init_inject_str - by default all imports are executed in this function and only the remainig code needed to be executed is returned to define the reload logic. str, str: init_inject_str, init_str - if return_initstr is True then also returns init_str defining the from imports. Ignore: ignore_startswith = [] ignore_endswith = [] check_not_imported = True verbose = True """ if verbose: print('[UTIL_IMPORT] Running Dynamic Imports for modname=%r ' % modname) # Get the module that will be imported into try: module = sys.modules[modname] except: module = __import__(modname) # List of modules to be imported imports = [tup[0] for tup in import_tuples] # Import the modules __excecute_imports(module, modname, imports, verbose=verbose) # If developing do explicit import stars if developing: from_imports = __execute_fromimport_star(module, modname, import_tuples, ignore_list=ignore_list, ignore_startswith=ignore_startswith, ignore_endswith=ignore_endswith, check_not_imported=check_not_imported, verbose=verbose) else: from_imports = __execute_fromimport(module, modname, import_tuples, verbose=verbose) inject_execstr = _inject_execstr(modname, import_tuples) # If requested: print what the __init__ module should look like dump_requested = (('--dump-%s-init' % modname) in sys.argv or ('--print-%s-init' % modname) in sys.argv) or dump overwrite_requested = ('--update-%s-init' % modname) in sys.argv if verbose: print('[UTIL_IMPORT] Finished Dynamic Imports for modname=%r ' % modname) if dump_requested: is_main_proc = multiprocessing.current_process().name == 'MainProcess' if is_main_proc: from utool import util_str initstr = _initstr(modname, imports, from_imports, inject_execstr) print(util_str.indent(initstr)) # Overwrite the __init__.py file with new explicit imports if overwrite_requested: """ SeeAlso: util_inject.inject_python_code util_str.replace_between_tags """ is_main_proc = multiprocessing.current_process().name == 'MainProcess' if is_main_proc: from utool import util_str from os.path import join, exists initstr = _initstr(modname, imports, from_imports, inject_execstr, withheader=False) new_else = util_str.indent(initstr) #print(new_else) # Get path to init file so we can overwrite it init_fpath = join(module.__path__[0], '__init__.py') print('attempting to update: %r' % init_fpath) assert exists(init_fpath) new_lines = [] editing = False updated = False #start_tag = '# <AUTOGEN_INIT>' #end_tag = '# </AUTOGEN_INIT>' with open(init_fpath, 'r') as file_: #text = file_.read() lines = file_.readlines() for line in lines: if not editing: new_lines.append(line) if line.strip().startswith('# <AUTOGEN_INIT>'): new_lines.append('\n' + new_else + '\n # </AUTOGEN_INIT>\n') editing = True updated = True if line.strip().startswith('# </AUTOGEN_INIT>'): editing = False # TODO: #new_text = util_str.replace_between_tags(text, new_else, start_tag, end_tag) if updated: print('writing updated file: %r' % init_fpath) new_text = ''.join(new_lines) with open(init_fpath, 'w') as file_: file_.write(new_text) else: print('no write hook for file: %r' % init_fpath) if return_initstr: initstr = _initstr(modname, imports, from_imports, '', withheader=False) return inject_execstr, initstr else: return inject_execstr
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 21; 2, function_name:write_to; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 3, 12; 3, 15; 3, 18; 4, identifier:fpath; 5, identifier:to_write; 6, default_parameter; 6, 7; 6, 8; 7, identifier:aslines; 8, False; 9, default_parameter; 9, 10; 9, 11; 10, identifier:verbose; 11, None; 12, default_parameter; 12, 13; 12, 14; 13, identifier:onlyifdiff; 14, False; 15, default_parameter; 15, 16; 15, 17; 16, identifier:mode; 17, string:'w'; 18, default_parameter; 18, 19; 18, 20; 19, identifier:n; 20, None; 21, block; 21, 22; 21, 24; 21, 56; 21, 63; 21, 78; 21, 87; 21, 100; 21, 118; 22, expression_statement; 22, 23; 23, comment; 24, if_statement; 24, 25; 24, 26; 25, identifier:onlyifdiff; 26, block; 26, 27; 26, 32; 27, import_statement; 27, 28; 28, aliased_import; 28, 29; 28, 31; 29, dotted_name; 29, 30; 30, identifier:utool; 31, identifier:ut; 32, if_statement; 32, 33; 32, 49; 33, comparison_operator:==; 33, 34; 33, 43; 34, call; 34, 35; 34, 38; 35, attribute; 35, 36; 35, 37; 36, identifier:ut; 37, identifier:hashstr; 38, argument_list; 38, 39; 39, call; 39, 40; 39, 41; 40, identifier:read_from; 41, argument_list; 41, 42; 42, identifier:fpath; 43, call; 43, 44; 43, 47; 44, attribute; 44, 45; 44, 46; 45, identifier:ut; 46, identifier:hashstr; 47, argument_list; 47, 48; 48, identifier:to_write; 49, block; 49, 50; 49, 55; 50, expression_statement; 50, 51; 51, call; 51, 52; 51, 53; 52, identifier:print; 53, argument_list; 53, 54; 54, string:'[util_io] * no difference'; 55, return_statement; 56, expression_statement; 56, 57; 57, assignment; 57, 58; 57, 59; 58, identifier:verbose; 59, call; 59, 60; 59, 61; 60, identifier:_rectify_verb_write; 61, argument_list; 61, 62; 62, identifier:verbose; 63, if_statement; 63, 64; 63, 65; 63, 66; 63, 67; 64, identifier:verbose; 65, comment; 66, comment; 67, block; 67, 68; 68, expression_statement; 68, 69; 69, call; 69, 70; 69, 71; 70, identifier:print; 71, argument_list; 71, 72; 72, call; 72, 73; 72, 76; 73, attribute; 73, 74; 73, 75; 74, string:'[util_io] * Writing to text file: {}'; 75, identifier:format; 76, argument_list; 76, 77; 77, identifier:fpath; 78, expression_statement; 78, 79; 79, assignment; 79, 80; 79, 81; 80, identifier:backup; 81, boolean_operator:and; 81, 82; 81, 83; 82, False; 83, call; 83, 84; 83, 85; 84, identifier:exists; 85, argument_list; 85, 86; 86, identifier:fpath; 87, if_statement; 87, 88; 87, 89; 88, identifier:backup; 89, block; 89, 90; 90, expression_statement; 90, 91; 91, call; 91, 92; 91, 95; 92, attribute; 92, 93; 92, 94; 93, identifier:util_path; 94, identifier:copy; 95, argument_list; 95, 96; 95, 97; 96, identifier:fpath; 97, binary_operator:+; 97, 98; 97, 99; 98, identifier:fpath; 99, string:'.backup'; 100, if_statement; 100, 101; 100, 109; 100, 110; 100, 111; 101, not_operator; 101, 102; 102, call; 102, 103; 102, 104; 103, identifier:isinstance; 104, argument_list; 104, 105; 104, 106; 105, identifier:fpath; 106, attribute; 106, 107; 106, 108; 107, identifier:six; 108, identifier:string_types; 109, comment; 110, comment; 111, block; 111, 112; 112, expression_statement; 112, 113; 113, assignment; 113, 114; 113, 115; 114, identifier:fpath; 115, attribute; 115, 116; 115, 117; 116, identifier:fpath; 117, identifier:name; 118, with_statement; 118, 119; 118, 129; 119, with_clause; 119, 120; 120, with_item; 120, 121; 121, as_pattern; 121, 122; 121, 127; 122, call; 122, 123; 122, 124; 123, identifier:open; 124, argument_list; 124, 125; 124, 126; 125, identifier:fpath; 126, identifier:mode; 127, as_pattern_target; 127, 128; 128, identifier:file_; 129, block; 129, 130; 130, if_statement; 130, 131; 130, 132; 130, 140; 131, identifier:aslines; 132, block; 132, 133; 133, expression_statement; 133, 134; 134, call; 134, 135; 134, 138; 135, attribute; 135, 136; 135, 137; 136, identifier:file_; 137, identifier:writelines; 138, argument_list; 138, 139; 139, identifier:to_write; 140, else_clause; 140, 141; 140, 142; 141, comment; 142, block; 142, 143; 142, 165; 143, if_statement; 143, 144; 143, 147; 144, attribute; 144, 145; 144, 146; 145, identifier:six; 146, identifier:PY2; 147, block; 147, 148; 148, if_statement; 148, 149; 148, 154; 148, 155; 149, call; 149, 150; 149, 151; 150, identifier:isinstance; 151, argument_list; 151, 152; 151, 153; 152, identifier:to_write; 153, identifier:unicode; 154, comment; 155, block; 155, 156; 156, expression_statement; 156, 157; 157, assignment; 157, 158; 157, 159; 158, identifier:to_write; 159, call; 159, 160; 159, 163; 160, attribute; 160, 161; 160, 162; 161, identifier:to_write; 162, identifier:encode; 163, argument_list; 163, 164; 164, string:'utf8'; 165, try_statement; 165, 166; 165, 174; 166, block; 166, 167; 167, expression_statement; 167, 168; 168, call; 168, 169; 168, 172; 169, attribute; 169, 170; 169, 171; 170, identifier:file_; 171, identifier:write; 172, argument_list; 172, 173; 173, identifier:to_write; 174, except_clause; 174, 175; 174, 179; 175, as_pattern; 175, 176; 175, 177; 176, identifier:UnicodeEncodeError; 177, as_pattern_target; 177, 178; 178, identifier:ex; 179, block; 179, 180; 179, 194; 179, 204; 179, 213; 179, 221; 179, 226; 179, 231; 179, 244; 179, 250; 179, 264; 179, 265; 179, 266; 180, expression_statement; 180, 181; 181, assignment; 181, 182; 181, 183; 182, identifier:start; 183, call; 183, 184; 183, 185; 184, identifier:max; 185, argument_list; 185, 186; 185, 193; 186, binary_operator:-; 186, 187; 186, 192; 187, subscript; 187, 188; 187, 191; 188, attribute; 188, 189; 188, 190; 189, identifier:ex; 190, identifier:args; 191, integer:2; 192, integer:10; 193, integer:0; 194, expression_statement; 194, 195; 195, assignment; 195, 196; 195, 197; 196, identifier:end; 197, binary_operator:+; 197, 198; 197, 203; 198, subscript; 198, 199; 198, 202; 199, attribute; 199, 200; 199, 201; 200, identifier:ex; 201, identifier:args; 202, integer:3; 203, integer:10; 204, expression_statement; 204, 205; 205, assignment; 205, 206; 205, 207; 206, identifier:context; 207, subscript; 207, 208; 207, 209; 208, identifier:to_write; 209, slice; 209, 210; 209, 211; 209, 212; 210, identifier:start; 211, colon; 212, identifier:end; 213, expression_statement; 213, 214; 214, call; 214, 215; 214, 216; 215, identifier:print; 216, argument_list; 216, 217; 217, call; 217, 218; 217, 219; 218, identifier:repr; 219, argument_list; 219, 220; 220, identifier:context; 221, expression_statement; 221, 222; 222, call; 222, 223; 222, 224; 223, identifier:print; 224, argument_list; 224, 225; 225, identifier:context; 226, import_from_statement; 226, 227; 226, 229; 227, dotted_name; 227, 228; 228, identifier:utool; 229, dotted_name; 229, 230; 230, identifier:util_dbg; 231, expression_statement; 231, 232; 232, call; 232, 233; 232, 236; 233, attribute; 233, 234; 233, 235; 234, identifier:util_dbg; 235, identifier:printex; 236, argument_list; 236, 237; 236, 238; 237, identifier:ex; 238, keyword_argument; 238, 239; 238, 240; 239, identifier:keys; 240, list:[(type, 'to_write')]; 240, 241; 241, tuple; 241, 242; 241, 243; 242, identifier:type; 243, string:'to_write'; 244, expression_statement; 244, 245; 245, call; 245, 246; 245, 249; 246, attribute; 246, 247; 246, 248; 247, identifier:file_; 248, identifier:close; 249, argument_list; 250, if_statement; 250, 251; 250, 252; 250, 253; 251, identifier:backup; 252, comment; 253, block; 253, 254; 254, expression_statement; 254, 255; 255, call; 255, 256; 255, 259; 256, attribute; 256, 257; 256, 258; 257, identifier:util_path; 258, identifier:copy; 259, argument_list; 259, 260; 259, 263; 260, binary_operator:+; 260, 261; 260, 262; 261, identifier:fpath; 262, string:'.backup'; 263, identifier:fpath; 264, comment; 265, comment; 266, raise_statement
def write_to(fpath, to_write, aslines=False, verbose=None, onlyifdiff=False, mode='w', n=None): """ Writes text to a file. Automatically encodes text as utf8. Args: fpath (str): file path to_write (str): text to write (must be unicode text) aslines (bool): if True to_write is assumed to be a list of lines verbose (bool): verbosity flag onlyifdiff (bool): only writes if needed! checks hash of to_write vs the hash of the contents of fpath mode (unicode): (default = u'w') n (int): (default = 2) CommandLine: python -m utool.util_io --exec-write_to --show Example: >>> # DISABLE_DOCTEST >>> from utool.util_io import * # NOQA >>> import utool as ut >>> fpath = ut.unixjoin(ut.get_app_resource_dir('utool'), 'testwrite.txt') >>> ut.delete(fpath) >>> to_write = 'utf-8 symbols Δ, Й, ק, م, ๗, あ, 叶, 葉, and 말.' >>> aslines = False >>> verbose = True >>> onlyifdiff = False >>> mode = u'w' >>> n = 2 >>> write_to(fpath, to_write, aslines, verbose, onlyifdiff, mode, n) >>> read_ = ut.read_from(fpath) >>> print('read_ = ' + read_) >>> print('to_write = ' + to_write) >>> assert read_ == to_write """ if onlyifdiff: import utool as ut if ut.hashstr(read_from(fpath)) == ut.hashstr(to_write): print('[util_io] * no difference') return verbose = _rectify_verb_write(verbose) if verbose: # n = None if verbose > 1 else 2 # print('[util_io] * Writing to text file: %r ' % util_path.tail(fpath, n=n)) print('[util_io] * Writing to text file: {}'.format(fpath)) backup = False and exists(fpath) if backup: util_path.copy(fpath, fpath + '.backup') if not isinstance(fpath, six.string_types): # Assuming a file object with a name attribute # Should just read from the file fpath = fpath.name with open(fpath, mode) as file_: if aslines: file_.writelines(to_write) else: # Ensure python2 writes in bytes if six.PY2: if isinstance(to_write, unicode): # NOQA to_write = to_write.encode('utf8') try: file_.write(to_write) except UnicodeEncodeError as ex: start = max(ex.args[2] - 10, 0) end = ex.args[3] + 10 context = to_write[start:end] print(repr(context)) print(context) from utool import util_dbg util_dbg.printex(ex, keys=[(type, 'to_write')]) file_.close() if backup: # restore util_path.copy(fpath + '.backup', fpath) # import utool # utool.embed() raise
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 20; 2, function_name:read_from; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 3, 14; 3, 17; 4, identifier:fpath; 5, default_parameter; 5, 6; 5, 7; 6, identifier:verbose; 7, None; 8, default_parameter; 8, 9; 8, 10; 9, identifier:aslines; 10, False; 11, default_parameter; 11, 12; 11, 13; 12, identifier:strict; 13, True; 14, default_parameter; 14, 15; 14, 16; 15, identifier:n; 16, None; 17, default_parameter; 17, 18; 17, 19; 18, identifier:errors; 19, string:'replace'; 20, block; 20, 21; 20, 23; 20, 32; 20, 39; 20, 57; 21, expression_statement; 21, 22; 22, comment; 23, if_statement; 23, 24; 23, 27; 24, comparison_operator:is; 24, 25; 24, 26; 25, identifier:n; 26, None; 27, block; 27, 28; 28, expression_statement; 28, 29; 29, assignment; 29, 30; 29, 31; 30, identifier:n; 31, identifier:__READ_TAIL_N__; 32, expression_statement; 32, 33; 33, assignment; 33, 34; 33, 35; 34, identifier:verbose; 35, call; 35, 36; 35, 37; 36, identifier:_rectify_verb_read; 37, argument_list; 37, 38; 38, identifier:verbose; 39, if_statement; 39, 40; 39, 41; 40, identifier:verbose; 41, block; 41, 42; 42, expression_statement; 42, 43; 43, call; 43, 44; 43, 45; 44, identifier:print; 45, argument_list; 45, 46; 46, binary_operator:%; 46, 47; 46, 48; 47, string:'[util_io] * Reading text file: %r '; 48, call; 48, 49; 48, 52; 49, attribute; 49, 50; 49, 51; 50, identifier:util_path; 51, identifier:tail; 52, argument_list; 52, 53; 52, 54; 53, identifier:fpath; 54, keyword_argument; 54, 55; 54, 56; 55, identifier:n; 56, identifier:n; 57, try_statement; 57, 58; 57, 191; 58, block; 58, 59; 58, 79; 58, 80; 58, 189; 59, if_statement; 59, 60; 59, 73; 60, not_operator; 60, 61; 61, call; 61, 62; 61, 65; 62, attribute; 62, 63; 62, 64; 63, identifier:util_path; 64, identifier:checkpath; 65, argument_list; 65, 66; 65, 67; 65, 70; 66, identifier:fpath; 67, keyword_argument; 67, 68; 67, 69; 68, identifier:verbose; 69, identifier:verbose; 70, keyword_argument; 70, 71; 70, 72; 71, identifier:n; 72, identifier:n; 73, block; 73, 74; 74, raise_statement; 74, 75; 75, call; 75, 76; 75, 77; 76, identifier:IOError; 77, argument_list; 77, 78; 78, string:'[io] * FILE DOES NOT EXIST!'; 79, comment; 80, with_statement; 80, 81; 80, 91; 81, with_clause; 81, 82; 82, with_item; 82, 83; 83, as_pattern; 83, 84; 83, 89; 84, call; 84, 85; 84, 86; 85, identifier:open; 86, argument_list; 86, 87; 86, 88; 87, identifier:fpath; 88, string:'rb'; 89, as_pattern_target; 89, 90; 90, identifier:file_; 91, block; 91, 92; 92, if_statement; 92, 93; 92, 94; 92, 95; 92, 146; 93, identifier:aslines; 94, comment; 95, block; 95, 96; 96, if_statement; 96, 97; 96, 100; 96, 101; 96, 102; 96, 123; 97, attribute; 97, 98; 97, 99; 98, identifier:six; 99, identifier:PY2; 100, comment; 101, comment; 102, block; 102, 103; 103, expression_statement; 103, 104; 104, assignment; 104, 105; 104, 106; 105, identifier:text; 106, list_comprehension; 106, 107; 106, 116; 107, call; 107, 108; 107, 111; 108, attribute; 108, 109; 108, 110; 109, identifier:line; 110, identifier:decode; 111, argument_list; 111, 112; 111, 113; 112, string:'utf8'; 113, keyword_argument; 113, 114; 113, 115; 114, identifier:errors; 115, identifier:errors; 116, for_in_clause; 116, 117; 116, 118; 117, identifier:line; 118, call; 118, 119; 118, 122; 119, attribute; 119, 120; 119, 121; 120, identifier:file_; 121, identifier:readlines; 122, argument_list; 123, else_clause; 123, 124; 124, block; 124, 125; 124, 145; 125, expression_statement; 125, 126; 126, assignment; 126, 127; 126, 128; 127, identifier:text; 128, list_comprehension; 128, 129; 128, 138; 129, call; 129, 130; 129, 133; 130, attribute; 130, 131; 130, 132; 131, identifier:line; 132, identifier:decode; 133, argument_list; 133, 134; 133, 135; 134, string:'utf8'; 135, keyword_argument; 135, 136; 135, 137; 136, identifier:errors; 137, identifier:errors; 138, for_in_clause; 138, 139; 138, 140; 139, identifier:line; 140, call; 140, 141; 140, 144; 141, attribute; 141, 142; 141, 143; 142, identifier:file_; 143, identifier:readlines; 144, argument_list; 145, comment; 146, else_clause; 146, 147; 146, 148; 147, comment; 148, block; 148, 149; 149, if_statement; 149, 150; 149, 153; 149, 170; 150, attribute; 150, 151; 150, 152; 151, identifier:six; 152, identifier:PY2; 153, block; 153, 154; 154, expression_statement; 154, 155; 155, assignment; 155, 156; 155, 157; 156, identifier:text; 157, call; 157, 158; 157, 165; 158, attribute; 158, 159; 158, 164; 159, call; 159, 160; 159, 163; 160, attribute; 160, 161; 160, 162; 161, identifier:file_; 162, identifier:read; 163, argument_list; 164, identifier:decode; 165, argument_list; 165, 166; 165, 167; 166, string:'utf8'; 167, keyword_argument; 167, 168; 167, 169; 168, identifier:errors; 169, identifier:errors; 170, else_clause; 170, 171; 170, 172; 171, comment; 172, block; 172, 173; 173, expression_statement; 173, 174; 174, assignment; 174, 175; 174, 176; 175, identifier:text; 176, call; 176, 177; 176, 184; 177, attribute; 177, 178; 177, 183; 178, call; 178, 179; 178, 182; 179, attribute; 179, 180; 179, 181; 180, identifier:file_; 181, identifier:read; 182, argument_list; 183, identifier:decode; 184, argument_list; 184, 185; 184, 186; 185, string:'utf8'; 186, keyword_argument; 186, 187; 186, 188; 187, identifier:errors; 188, identifier:errors; 189, return_statement; 189, 190; 190, identifier:text; 191, except_clause; 191, 192; 191, 196; 192, as_pattern; 192, 193; 192, 194; 193, identifier:IOError; 194, as_pattern_target; 194, 195; 195, identifier:ex; 196, block; 196, 197; 196, 202; 196, 226; 197, import_from_statement; 197, 198; 197, 200; 198, dotted_name; 198, 199; 199, identifier:utool; 200, dotted_name; 200, 201; 201, identifier:util_dbg; 202, if_statement; 202, 203; 202, 206; 203, boolean_operator:or; 203, 204; 203, 205; 204, identifier:verbose; 205, identifier:strict; 206, block; 206, 207; 207, expression_statement; 207, 208; 208, call; 208, 209; 208, 212; 209, attribute; 209, 210; 209, 211; 210, identifier:util_dbg; 211, identifier:printex; 212, argument_list; 212, 213; 212, 214; 212, 225; 213, identifier:ex; 214, binary_operator:%; 214, 215; 214, 216; 215, string:' * Error reading fpath=%r'; 216, call; 216, 217; 216, 220; 217, attribute; 217, 218; 217, 219; 218, identifier:util_path; 219, identifier:tail; 220, argument_list; 220, 221; 220, 222; 221, identifier:fpath; 222, keyword_argument; 222, 223; 222, 224; 223, identifier:n; 224, identifier:n; 225, string:'[io]'; 226, if_statement; 226, 227; 226, 228; 227, identifier:strict; 228, block; 228, 229; 229, raise_statement
def read_from(fpath, verbose=None, aslines=False, strict=True, n=None, errors='replace'): r""" Reads text from a file. Automatically returns utf8. Args: fpath (str): file path aslines (bool): if True returns list of lines verbose (bool): verbosity flag Returns: str: text from fpath (this is unicode) Ignore: x = b'''/whaleshark_003_fors\xc3\xb8g.wmv" />\r\n''' ut.writeto('foo.txt', x) y = ut.readfrom('foo.txt') y.encode('utf8') == x """ if n is None: n = __READ_TAIL_N__ verbose = _rectify_verb_read(verbose) if verbose: print('[util_io] * Reading text file: %r ' % util_path.tail(fpath, n=n)) try: if not util_path.checkpath(fpath, verbose=verbose, n=n): raise IOError('[io] * FILE DOES NOT EXIST!') #with open(fpath, 'r') as file_: with open(fpath, 'rb') as file_: if aslines: #text = file_.readlines() if six.PY2: # python2 writes in bytes, so read as bytes then convert to # utf8 text = [line.decode('utf8', errors=errors) for line in file_.readlines()] else: text = [line.decode('utf8', errors=errors) for line in file_.readlines()] #text = file_.readlines() else: # text = file_.read() if six.PY2: text = file_.read().decode('utf8', errors=errors) else: #text = file_.read() text = file_.read().decode('utf8', errors=errors) return text except IOError as ex: from utool import util_dbg if verbose or strict: util_dbg.printex(ex, ' * Error reading fpath=%r' % util_path.tail(fpath, n=n), '[io]') if strict: raise
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 11; 2, function_name:load_cPkl; 3, parameters; 3, 4; 3, 5; 3, 8; 4, identifier:fpath; 5, default_parameter; 5, 6; 5, 7; 6, identifier:verbose; 7, None; 8, default_parameter; 8, 9; 8, 10; 9, identifier:n; 10, None; 11, block; 11, 12; 11, 14; 11, 21; 11, 40; 11, 133; 12, expression_statement; 12, 13; 13, comment; 14, expression_statement; 14, 15; 15, assignment; 15, 16; 15, 17; 16, identifier:verbose; 17, call; 17, 18; 17, 19; 18, identifier:_rectify_verb_read; 19, argument_list; 19, 20; 20, identifier:verbose; 21, if_statement; 21, 22; 21, 23; 22, identifier:verbose; 23, block; 23, 24; 24, expression_statement; 24, 25; 25, call; 25, 26; 25, 27; 26, identifier:print; 27, argument_list; 27, 28; 28, binary_operator:%; 28, 29; 28, 30; 29, string:'[util_io] * load_cPkl(%r)'; 30, tuple; 30, 31; 31, call; 31, 32; 31, 35; 32, attribute; 32, 33; 32, 34; 33, identifier:util_path; 34, identifier:tail; 35, argument_list; 35, 36; 35, 37; 36, identifier:fpath; 37, keyword_argument; 37, 38; 37, 39; 38, identifier:n; 39, identifier:n; 40, try_statement; 40, 41; 40, 63; 40, 99; 41, block; 41, 42; 42, with_statement; 42, 43; 42, 53; 43, with_clause; 43, 44; 44, with_item; 44, 45; 45, as_pattern; 45, 46; 45, 51; 46, call; 46, 47; 46, 48; 47, identifier:open; 48, argument_list; 48, 49; 48, 50; 49, identifier:fpath; 50, string:'rb'; 51, as_pattern_target; 51, 52; 52, identifier:file_; 53, block; 53, 54; 54, expression_statement; 54, 55; 55, assignment; 55, 56; 55, 57; 56, identifier:data; 57, call; 57, 58; 57, 61; 58, attribute; 58, 59; 58, 60; 59, identifier:pickle; 60, identifier:load; 61, argument_list; 61, 62; 62, identifier:file_; 63, except_clause; 63, 64; 63, 65; 64, identifier:UnicodeDecodeError; 65, block; 65, 66; 66, if_statement; 66, 67; 66, 70; 66, 71; 66, 96; 67, attribute; 67, 68; 67, 69; 68, identifier:six; 69, identifier:PY3; 70, comment; 71, block; 71, 72; 72, with_statement; 72, 73; 72, 83; 73, with_clause; 73, 74; 74, with_item; 74, 75; 75, as_pattern; 75, 76; 75, 81; 76, call; 76, 77; 76, 78; 77, identifier:open; 78, argument_list; 78, 79; 78, 80; 79, identifier:fpath; 80, string:'rb'; 81, as_pattern_target; 81, 82; 82, identifier:file_; 83, block; 83, 84; 84, expression_statement; 84, 85; 85, assignment; 85, 86; 85, 87; 86, identifier:data; 87, call; 87, 88; 87, 91; 88, attribute; 88, 89; 88, 90; 89, identifier:pickle; 90, identifier:load; 91, argument_list; 91, 92; 91, 93; 92, identifier:file_; 93, keyword_argument; 93, 94; 93, 95; 94, identifier:encoding; 95, string:'latin1'; 96, else_clause; 96, 97; 97, block; 97, 98; 98, raise_statement; 99, except_clause; 99, 100; 99, 104; 100, as_pattern; 100, 101; 100, 102; 101, identifier:ValueError; 102, as_pattern_target; 102, 103; 103, identifier:ex; 104, block; 104, 105; 105, if_statement; 105, 106; 105, 109; 105, 130; 106, attribute; 106, 107; 106, 108; 107, identifier:six; 108, identifier:PY2; 109, block; 109, 110; 110, if_statement; 110, 111; 110, 116; 110, 127; 111, comparison_operator:==; 111, 112; 111, 115; 112, attribute; 112, 113; 112, 114; 113, identifier:ex; 114, identifier:message; 115, string:'unsupported pickle protocol: 4'; 116, block; 116, 117; 117, raise_statement; 117, 118; 118, call; 118, 119; 118, 120; 119, identifier:ValueError; 120, argument_list; 120, 121; 121, binary_operator:%; 121, 122; 121, 125; 122, concatenated_string; 122, 123; 122, 124; 123, string:'unsupported Python3 pickle protocol 4 '; 124, string:'in Python2 for fpath=%r'; 125, tuple; 125, 126; 126, identifier:fpath; 127, else_clause; 127, 128; 128, block; 128, 129; 129, raise_statement; 130, else_clause; 130, 131; 131, block; 131, 132; 132, raise_statement; 133, return_statement; 133, 134; 134, identifier:data
def load_cPkl(fpath, verbose=None, n=None): """ Loads a pickled file with optional verbosity. Aims for compatibility between python2 and python3. TestPickleExtentsSimple: >>> def makedata_simple(): >>> data = np.empty((500, 2 ** 20), dtype=np.uint8) + 1 >>> return data >>> memtrack = ut.MemoryTracker() >>> # create a large amount of data >>> data = makedata_simple() >>> memtrack.report() >>> print(ut.get_object_size_str(data)) >>> fpath = 'tmp.pkl' >>> ut.save_cPkl(fpath, data) >>> print(ut.get_file_nBytes_str('tmp.pkl')) >>> #del data >>> memtrack.collect() >>> memtrack.report() >>> data = ut.load_cPkl(fpath) >>> memtrack.report() TestPickleExtentsComplex: >>> def makedata_complex(): >>> rng = np.random.RandomState(42) >>> item1 = np.empty((100, 2 ** 20), dtype=np.uint8) + 1 >>> item2 = [np.empty((10, 2 ** 10), dtype=np.uint8) + 1 >>> for a in range(1000)] >>> item3 = {a: np.empty(int(rng.rand() * 10), dtype=np.int16) + 1 >>> for a in range(100)} >>> item4 = {np.int32(a): np.empty((int(rng.rand() * 10), 2), dtype=np.float64) + 1 >>> for a in range(200)} >>> data = {'item1': item1, 'item2': item2, >>> 'item3': item3, 'item4': item4} >>> return data >>> memtrack = ut.MemoryTracker() >>> # create a large amount of data >>> data = makedata_complex() >>> memtrack.report() >>> print(ut.get_object_size_str(data)) >>> fpath = 'tmp.pkl' >>> ut.save_cPkl(fpath, data) >>> print(ut.get_file_nBytes_str('tmp.pkl')) >>> #del data >>> memtrack.collect() >>> memtrack.report() >>> data2 = ut.load_cPkl(fpath) >>> memtrack.report() TestPickleCacher: >>> memtrack = ut.MemoryTracker() >>> cacher = ut.Cacher('tmp', cache_dir='.', cfgstr='foo') >>> data3 = cacher.ensure(makedata_complex) >>> memtrack.report() >>> data4 = cacher.ensure(makedata_complex) >>> memtrack.report() >>> memtrack = ut.MemoryTracker() >>> fpath = '/home/joncrall/Desktop/smkcache/inva_PZ_Master1VUUIDS((5616)vxihbjwtggyovrto)_vpgwpcafbjkkpjdf.cPkl' >>> print(ut.get_file_nBytes_str(fpath)) >>> data = ut.load_cPkl(fpath) >>> memtrack.report() def makedata_complex(): data = np.empty((1000, 2 ** 20), dtype=np.uint8) data[:] = 0 return data """ verbose = _rectify_verb_read(verbose) if verbose: print('[util_io] * load_cPkl(%r)' % (util_path.tail(fpath, n=n),)) try: with open(fpath, 'rb') as file_: data = pickle.load(file_) except UnicodeDecodeError: if six.PY3: # try to open python2 pickle with open(fpath, 'rb') as file_: data = pickle.load(file_, encoding='latin1') else: raise except ValueError as ex: if six.PY2: if ex.message == 'unsupported pickle protocol: 4': raise ValueError( 'unsupported Python3 pickle protocol 4 ' 'in Python2 for fpath=%r' % (fpath,)) else: raise else: raise return data
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 12; 2, function_name:save_hdf5; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 4, identifier:fpath; 5, identifier:data; 6, default_parameter; 6, 7; 6, 8; 7, identifier:verbose; 8, None; 9, default_parameter; 9, 10; 9, 11; 10, identifier:compression; 11, string:'lzf'; 12, block; 12, 13; 12, 15; 12, 18; 12, 25; 12, 41; 12, 83; 12, 87; 12, 88; 12, 95; 12, 96; 12, 97; 12, 98; 12, 99; 12, 100; 12, 101; 12, 102; 12, 103; 12, 107; 13, expression_statement; 13, 14; 14, comment; 15, import_statement; 15, 16; 16, dotted_name; 16, 17; 17, identifier:h5py; 18, expression_statement; 18, 19; 19, assignment; 19, 20; 19, 21; 20, identifier:verbose; 21, call; 21, 22; 21, 23; 22, identifier:_rectify_verb_write; 23, argument_list; 23, 24; 24, identifier:verbose; 25, if_statement; 25, 26; 25, 27; 26, identifier:verbose; 27, block; 27, 28; 28, expression_statement; 28, 29; 29, call; 29, 30; 29, 31; 30, identifier:print; 31, argument_list; 31, 32; 32, binary_operator:%; 32, 33; 32, 34; 33, string:'[util_io] * save_hdf5(%r, data)'; 34, tuple; 34, 35; 35, call; 35, 36; 35, 39; 36, attribute; 36, 37; 36, 38; 37, identifier:util_path; 38, identifier:tail; 39, argument_list; 39, 40; 40, identifier:fpath; 41, if_statement; 41, 42; 41, 45; 42, comparison_operator:>; 42, 43; 42, 44; 43, identifier:verbose; 44, integer:1; 45, block; 45, 46; 46, if_statement; 46, 47; 46, 52; 46, 71; 47, call; 47, 48; 47, 49; 48, identifier:isinstance; 49, argument_list; 49, 50; 49, 51; 50, identifier:data; 51, identifier:dict; 52, block; 52, 53; 53, expression_statement; 53, 54; 54, call; 54, 55; 54, 56; 55, identifier:print; 56, argument_list; 56, 57; 57, binary_operator:%; 57, 58; 57, 59; 58, string:'[util_io] ... shapes=%r'; 59, tuple; 59, 60; 60, list_comprehension; 60, 61; 60, 64; 61, attribute; 61, 62; 61, 63; 62, identifier:val; 63, identifier:shape; 64, for_in_clause; 64, 65; 64, 66; 65, identifier:val; 66, call; 66, 67; 66, 70; 67, attribute; 67, 68; 67, 69; 68, identifier:data; 69, identifier:values; 70, argument_list; 71, else_clause; 71, 72; 72, block; 72, 73; 73, expression_statement; 73, 74; 74, call; 74, 75; 74, 76; 75, identifier:print; 76, argument_list; 76, 77; 77, binary_operator:%; 77, 78; 77, 79; 78, string:'[util_io] ... shape=%r'; 79, tuple; 79, 80; 80, attribute; 80, 81; 80, 82; 81, identifier:data; 82, identifier:shape; 83, expression_statement; 83, 84; 84, assignment; 84, 85; 84, 86; 85, identifier:chunks; 86, True; 87, comment; 88, expression_statement; 88, 89; 89, assignment; 89, 90; 89, 91; 90, identifier:fname; 91, call; 91, 92; 91, 93; 92, identifier:basename; 93, argument_list; 93, 94; 94, identifier:fpath; 95, comment; 96, comment; 97, comment; 98, comment; 99, comment; 100, comment; 101, comment; 102, comment; 103, expression_statement; 103, 104; 104, assignment; 104, 105; 104, 106; 105, identifier:h5kw; 106, dictionary; 107, if_statement; 107, 108; 107, 113; 107, 258; 108, call; 108, 109; 108, 110; 109, identifier:isinstance; 110, argument_list; 110, 111; 110, 112; 111, identifier:data; 112, identifier:dict; 113, block; 113, 114; 113, 140; 113, 160; 113, 161; 113, 162; 113, 163; 113, 164; 113, 165; 114, expression_statement; 114, 115; 115, assignment; 115, 116; 115, 117; 116, identifier:array_data; 117, dictionary_comprehension; 117, 118; 117, 121; 117, 130; 118, pair; 118, 119; 118, 120; 119, identifier:key; 120, identifier:val; 121, for_in_clause; 121, 122; 121, 125; 122, pattern_list; 122, 123; 122, 124; 123, identifier:key; 124, identifier:val; 125, call; 125, 126; 125, 129; 126, attribute; 126, 127; 126, 128; 127, identifier:data; 128, identifier:items; 129, argument_list; 130, if_clause; 130, 131; 131, call; 131, 132; 131, 133; 132, identifier:isinstance; 133, argument_list; 133, 134; 133, 135; 134, identifier:val; 135, tuple; 135, 136; 135, 137; 136, identifier:list; 137, attribute; 137, 138; 137, 139; 138, identifier:np; 139, identifier:ndarray; 140, expression_statement; 140, 141; 141, assignment; 141, 142; 141, 143; 142, identifier:attr_data; 143, dictionary_comprehension; 143, 144; 143, 147; 143, 156; 144, pair; 144, 145; 144, 146; 145, identifier:key; 146, identifier:val; 147, for_in_clause; 147, 148; 147, 151; 148, pattern_list; 148, 149; 148, 150; 149, identifier:key; 150, identifier:val; 151, call; 151, 152; 151, 155; 152, attribute; 152, 153; 152, 154; 153, identifier:data; 154, identifier:items; 155, argument_list; 156, if_clause; 156, 157; 157, comparison_operator:not; 157, 158; 157, 159; 158, identifier:key; 159, identifier:array_data; 160, comment; 161, comment; 162, comment; 163, comment; 164, comment; 165, with_statement; 165, 166; 165, 182; 166, with_clause; 166, 167; 167, with_item; 167, 168; 168, as_pattern; 168, 169; 168, 180; 169, call; 169, 170; 169, 173; 170, attribute; 170, 171; 170, 172; 171, identifier:h5py; 172, identifier:File; 173, argument_list; 173, 174; 173, 175; 173, 178; 174, identifier:fpath; 175, keyword_argument; 175, 176; 175, 177; 176, identifier:mode; 177, string:'w'; 178, dictionary_splat; 178, 179; 179, identifier:h5kw; 180, as_pattern_target; 180, 181; 181, identifier:file_; 182, block; 182, 183; 182, 192; 182, 239; 183, expression_statement; 183, 184; 184, assignment; 184, 185; 184, 186; 185, identifier:grp; 186, call; 186, 187; 186, 190; 187, attribute; 187, 188; 187, 189; 188, identifier:file_; 189, identifier:create_group; 190, argument_list; 190, 191; 191, identifier:fname; 192, for_statement; 192, 193; 192, 196; 192, 202; 193, pattern_list; 193, 194; 193, 195; 194, identifier:key; 195, identifier:val; 196, call; 196, 197; 196, 200; 197, attribute; 197, 198; 197, 199; 198, identifier:six; 199, identifier:iteritems; 200, argument_list; 200, 201; 201, identifier:array_data; 202, block; 202, 203; 202, 212; 202, 233; 203, expression_statement; 203, 204; 204, assignment; 204, 205; 204, 206; 205, identifier:val; 206, call; 206, 207; 206, 210; 207, attribute; 207, 208; 207, 209; 208, identifier:np; 209, identifier:asarray; 210, argument_list; 210, 211; 211, identifier:val; 212, expression_statement; 212, 213; 213, assignment; 213, 214; 213, 215; 214, identifier:dset; 215, call; 215, 216; 215, 219; 216, attribute; 216, 217; 216, 218; 217, identifier:grp; 218, identifier:create_dataset; 219, argument_list; 219, 220; 219, 221; 219, 224; 219, 227; 219, 230; 220, identifier:key; 221, attribute; 221, 222; 221, 223; 222, identifier:val; 223, identifier:shape; 224, attribute; 224, 225; 224, 226; 225, identifier:val; 226, identifier:dtype; 227, keyword_argument; 227, 228; 227, 229; 228, identifier:chunks; 229, identifier:chunks; 230, keyword_argument; 230, 231; 230, 232; 231, identifier:compression; 232, identifier:compression; 233, expression_statement; 233, 234; 234, assignment; 234, 235; 234, 238; 235, subscript; 235, 236; 235, 237; 236, identifier:dset; 237, ellipsis:...; 238, identifier:val; 239, for_statement; 239, 240; 239, 243; 239, 249; 240, pattern_list; 240, 241; 240, 242; 241, identifier:key; 242, identifier:val; 243, call; 243, 244; 243, 247; 244, attribute; 244, 245; 244, 246; 245, identifier:six; 246, identifier:iteritems; 247, argument_list; 247, 248; 248, identifier:attr_data; 249, block; 249, 250; 250, expression_statement; 250, 251; 251, assignment; 251, 252; 251, 257; 252, subscript; 252, 253; 252, 256; 253, attribute; 253, 254; 253, 255; 254, identifier:grp; 255, identifier:attrs; 256, identifier:key; 257, identifier:val; 258, else_clause; 258, 259; 259, block; 259, 260; 259, 268; 259, 274; 259, 280; 259, 281; 259, 282; 259, 283; 260, assert_statement; 260, 261; 261, call; 261, 262; 261, 263; 262, identifier:isinstance; 263, argument_list; 263, 264; 263, 265; 264, identifier:data; 265, attribute; 265, 266; 265, 267; 266, identifier:np; 267, identifier:ndarray; 268, expression_statement; 268, 269; 269, assignment; 269, 270; 269, 271; 270, identifier:shape; 271, attribute; 271, 272; 271, 273; 272, identifier:data; 273, identifier:shape; 274, expression_statement; 274, 275; 275, assignment; 275, 276; 275, 277; 276, identifier:dtype; 277, attribute; 277, 278; 277, 279; 278, identifier:data; 279, identifier:dtype; 280, comment; 281, comment; 282, comment; 283, with_statement; 283, 284; 283, 300; 283, 301; 283, 302; 283, 303; 284, with_clause; 284, 285; 285, with_item; 285, 286; 286, as_pattern; 286, 287; 286, 298; 287, call; 287, 288; 287, 291; 288, attribute; 288, 289; 288, 290; 289, identifier:h5py; 290, identifier:File; 291, argument_list; 291, 292; 291, 293; 291, 296; 292, identifier:fpath; 293, keyword_argument; 293, 294; 293, 295; 294, identifier:mode; 295, string:'w'; 296, dictionary_splat; 296, 297; 297, identifier:h5kw; 298, as_pattern_target; 298, 299; 299, identifier:file_; 300, comment; 301, comment; 302, comment; 303, block; 303, 304; 303, 321; 304, expression_statement; 304, 305; 305, assignment; 305, 306; 305, 307; 306, identifier:dset; 307, call; 307, 308; 307, 311; 308, attribute; 308, 309; 308, 310; 309, identifier:file_; 310, identifier:create_dataset; 311, argument_list; 311, 312; 311, 313; 311, 314; 311, 315; 311, 318; 312, identifier:fname; 313, identifier:shape; 314, identifier:dtype; 315, keyword_argument; 315, 316; 315, 317; 316, identifier:chunks; 317, identifier:chunks; 318, keyword_argument; 318, 319; 318, 320; 319, identifier:compression; 320, identifier:compression; 321, expression_statement; 321, 322; 322, assignment; 322, 323; 322, 326; 323, subscript; 323, 324; 323, 325; 324, identifier:dset; 325, ellipsis:...; 326, identifier:data
def save_hdf5(fpath, data, verbose=None, compression='lzf'): r""" Restricted save of data using hdf5. Can only save ndarrays and dicts of ndarrays. Args: fpath (str): data (ndarray): compression (str): DEFLATE/GZIP - standard LZF - fast SHUFFLE - compression ratio FLETCHER32 - error detection Scale-offset - integer / float scaling and truncation SZIP - fast and patented CommandLine: python -m utool.util_io --test-save_hdf5 References: http://docs.h5py.org/en/latest/quick.html http://docs.h5py.org/en/latest/mpi.html Example: >>> # DISABLE_DOCTEST >>> from utool.util_io import * # NOQA >>> import numpy as np >>> import utool as ut >>> rng = np.random.RandomState(0) >>> data = (rng.rand(100000, 128) * 255).astype(np.uint8).copy() >>> verbose = True >>> fpath = ut.unixjoin(ut.ensure_app_resource_dir('utool'), 'myfile.hdf5') >>> compression = 'lzf' >>> ut.delete(fpath) >>> save_hdf5(fpath, data, verbose, compression) >>> data2 = load_hdf5(fpath, verbose) >>> assert data is not data2 >>> assert np.all(data == data2) >>> assert ut.delete(fpath) Example: >>> # DISABLE_DOCTEST >>> from utool.util_io import * # NOQA >>> import numpy as np >>> import utool as ut >>> rng = np.random.RandomState(0) >>> data = {'name': 'foobar', 'x': [1, 2, 3], 'y': np.array([3, 2, 1])} >>> ut.exec_funckw(save_hdf5, globals()) >>> fpath = ut.unixjoin(ut.ensure_app_resource_dir('utool'), 'myfile2.hdf5') >>> ut.delete(fpath) >>> save_hdf5(fpath, data, verbose, compression) >>> data2 = load_hdf5(fpath, verbose) >>> assert data is not data2 >>> assert all([np.all(data[key] == data2[key]) for key in data.keys()]) >>> assert ut.delete(fpath) Timeit: >>> # DISABLE_DOCTEST >>> # cPkl / numpy seems to be faster with this initial implementation >>> import utool as ut >>> data = (rng.rand(1000000, 128) * 255).astype(np.uint8).copy() >>> print(ut.get_object_size_str(data)) >>> del data >>> setup = ut.codeblock( >>> ''' import numpy as np import utool as ut rng = np.random.RandomState(0) fpath = ut.unixjoin(ut.ensure_app_resource_dir('utool'), 'io_test_data') data = (rng.rand(1000000, 128) * 255).astype(np.uint8).copy() #print(ut.get_object_size_str(data)) ''') >>> # Test load time >>> stmt_list1 = ut.codeblock( >>> ''' ut.save_hdf5(fpath + '.hdf5', data, verbose=False, compression='gzip') ut.save_hdf5(fpath + '.hdf5', data, verbose=False, compression='lzf') ut.save_cPkl(fpath + '.cPkl', data, verbose=False) ut.save_numpy(fpath + '.npy', data, verbose=False) ut.save_pytables(fpath + '.tables', data, verbose=False) ''').split('\n') >>> ut.util_dev.timeit_compare(stmt_list1, setup, int(10)) >>> # Test save time >>> stmt_list2 = ut.codeblock( >>> ''' ut.load_hdf5(fpath + '.hdf5', verbose=False) ut.load_cPkl(fpath + '.cPkl', verbose=False) ut.load_numpy(fpath + '.npy', verbose=False) ut.load_pytables(fpath + '.tables', verbose=False) ''').split('\n') >>> ut.util_dev.timeit_compare(stmt_list2, setup, int(10)) >>> print('finished timeing') +---------------- | TIMEIT COMPARE +---------------- | iterations = 10 | Input: | | num | stmt | | 0 | u"ut.save_hdf5(fpath + '.hdf5', data, verbose=False, compression='gzip')" | | 1 | u"ut.save_hdf5(fpath + '.hdf5', data, verbose=False, compression='lzf')" | | 2 | u"ut.save_cPkl(fpath + '.cPkl', data, verbose=False)" | | 3 | u"ut.save_numpy(fpath + '.npy', data, verbose=False)" | | 4 | u"ut.save_pytables(fpath + '.tables', data, verbose=False)" ... | Output: | * PASSED: each statement produced the same result | | num | total time | per loop | stmt | | 0 | 0.03 ks | 3.15 s | ut.save_hdf5(fpath + '.hdf5', data, verbose=False, compression='gzip') | | 1 | 0.01 ks | 1.25 s | ut.save_hdf5(fpath + '.hdf5', data, verbose=False, compression='lzf') | | 2 | 5.30 s | 0.53 s | ut.save_cPkl(fpath + '.cPkl', data, verbose=False) | | 3 | 4.97 s | 0.50 s | ut.save_numpy(fpath + '.npy', data, verbose=False) | | 4 | 9.23 s | 0.92 s | ut.save_pytables(fpath + '.tables', data, verbose=False) L_________________ +---------------- | TIMEIT COMPARE +---------------- | iterations = 10 | Input: | | num | stmt | | 0 | u"ut.load_hdf5(fpath + '.hdf5', verbose=False)" | | 1 | u"ut.load_cPkl(fpath + '.cPkl', verbose=False)" | | 2 | u"ut.load_numpy(fpath + '.npy', verbose=False)" | | 3 | u"ut.load_pytables(fpath + '.tables', verbose=False)" ... | Output: | * PASSED: each statement produced the same result | | num | total time | per loop | stmt | | 0 | 2.39 s | 0.24 s | ut.load_hdf5(fpath + '.hdf5', verbose=False) | | 1 | 0.39 s | 0.04 s | ut.load_cPkl(fpath + '.cPkl', verbose=False) | | 2 | 0.19 s | 0.02 s | ut.load_numpy(fpath + '.npy', verbose=False) | | 3 | 0.33 s | 0.03 s | ut.load_pytables(fpath + '.tables', verbose=False) L_________________ Ignore: %timeit save_hdf5(fpath, data, verbose=False, compression='gzip') %timeit save_hdf5(fpath, data, verbose=False, compression='lzf') %timeit save_cPkl(fpath + '.cPkl', data, verbose=False) %timeit save_pytables(fpath + '.tables', data, verbose=False) 1 loops, best of 3: 258 ms per loop 10 loops, best of 3: 111 ms per loop 10 loops, best of 3: 53.1 ms per loop 10 loops, best of 3: 96.5 ms per loop save_hdf5(fpath, data, verbose=False, compression='gzip') %timeit load_hdf5(fpath, verbose=False) save_hdf5(fpath, data, verbose=False, compression='lzf') %timeit load_hdf5(fpath, verbose=False) %timeit load_cPkl(fpath + '.cPkl', verbose=False) %timeit load_pytables(fpath + '.tables', verbose=False) 100 loops, best of 3: 19.4 ms per loop 100 loops, best of 3: 14.4 ms per loop 100 loops, best of 3: 3.92 ms per loop 100 loops, best of 3: 6.22 ms per loop Notes: pip install mpi4py """ import h5py verbose = _rectify_verb_write(verbose) if verbose: print('[util_io] * save_hdf5(%r, data)' % (util_path.tail(fpath),)) if verbose > 1: if isinstance(data, dict): print('[util_io] ... shapes=%r' % ([val.shape for val in data.values()],)) else: print('[util_io] ... shape=%r' % (data.shape,)) chunks = True # True enables auto-chunking fname = basename(fpath) # check for parallel hdf5 #have_mpi = h5py.h5.get_config().mpi #if have_mpi: # import mpi4py # h5kw = dict(driver='mpio', comm=mpi4py.MPI.COMM_WORLD) # # cant use compression with mpi # #ValueError: Unable to create dataset (Parallel i/o does not support filters yet) #else: h5kw = {} if isinstance(data, dict): array_data = {key: val for key, val in data.items() if isinstance(val, (list, np.ndarray))} attr_data = {key: val for key, val in data.items() if key not in array_data} #assert all([ # isinstance(vals, np.ndarray) # for vals in six.itervalues(data) #]), ('can only save dicts as ndarrays') # file_ = h5py.File(fpath, 'w', **h5kw) with h5py.File(fpath, mode='w', **h5kw) as file_: grp = file_.create_group(fname) for key, val in six.iteritems(array_data): val = np.asarray(val) dset = grp.create_dataset( key, val.shape, val.dtype, chunks=chunks, compression=compression) dset[...] = val for key, val in six.iteritems(attr_data): grp.attrs[key] = val else: assert isinstance(data, np.ndarray) shape = data.shape dtype = data.dtype #if verbose or (verbose is None and __PRINT_WRITES__): # print('[util_io] * save_hdf5(%r, data)' % (util_path.tail(fpath),)) # file_ = h5py.File(fpath, 'w', **h5kw) with h5py.File(fpath, mode='w', **h5kw) as file_: #file_.create_dataset( # fname, shape, dtype, chunks=chunks, compression=compression, # data=data) dset = file_.create_dataset( fname, shape, dtype, chunks=chunks, compression=compression) dset[...] = data
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 32; 2, function_name:formatex; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 3, 14; 3, 17; 3, 20; 3, 23; 3, 26; 3, 29; 4, identifier:ex; 5, default_parameter; 5, 6; 5, 7; 6, identifier:msg; 7, string:'[!?] Caught exception'; 8, default_parameter; 8, 9; 8, 10; 9, identifier:prefix; 10, None; 11, default_parameter; 11, 12; 11, 13; 12, identifier:key_list; 13, list:[]; 14, default_parameter; 14, 15; 14, 16; 15, identifier:locals_; 16, None; 17, default_parameter; 17, 18; 17, 19; 18, identifier:iswarning; 19, False; 20, default_parameter; 20, 21; 20, 22; 21, identifier:tb; 22, False; 23, default_parameter; 23, 24; 23, 25; 24, identifier:N; 25, integer:0; 26, default_parameter; 26, 27; 26, 28; 27, identifier:keys; 28, None; 29, default_parameter; 29, 30; 29, 31; 30, identifier:colored; 31, None; 32, block; 32, 33; 32, 35; 32, 36; 32, 53; 32, 69; 32, 79; 32, 80; 32, 84; 32, 85; 32, 92; 32, 101; 32, 146; 32, 176; 32, 177; 32, 185; 32, 194; 33, expression_statement; 33, 34; 34, comment; 35, comment; 36, if_statement; 36, 37; 36, 40; 37, comparison_operator:is; 37, 38; 37, 39; 38, identifier:prefix; 39, None; 40, block; 40, 41; 41, expression_statement; 41, 42; 42, assignment; 42, 43; 42, 44; 43, identifier:prefix; 44, call; 44, 45; 44, 46; 45, identifier:get_caller_prefix; 46, argument_list; 46, 47; 46, 50; 47, keyword_argument; 47, 48; 47, 49; 48, identifier:aserror; 49, True; 50, keyword_argument; 50, 51; 50, 52; 51, identifier:N; 52, identifier:N; 53, if_statement; 53, 54; 53, 57; 54, comparison_operator:is; 54, 55; 54, 56; 55, identifier:locals_; 56, None; 57, block; 57, 58; 58, expression_statement; 58, 59; 59, assignment; 59, 60; 59, 61; 60, identifier:locals_; 61, attribute; 61, 62; 61, 68; 62, call; 62, 63; 62, 64; 63, identifier:get_parent_frame; 64, argument_list; 64, 65; 65, keyword_argument; 65, 66; 65, 67; 66, identifier:N; 67, identifier:N; 68, identifier:f_locals; 69, if_statement; 69, 70; 69, 73; 69, 74; 70, comparison_operator:is; 70, 71; 70, 72; 71, identifier:keys; 72, None; 73, comment; 74, block; 74, 75; 75, expression_statement; 75, 76; 76, assignment; 76, 77; 76, 78; 77, identifier:key_list; 78, identifier:keys; 79, comment; 80, expression_statement; 80, 81; 81, assignment; 81, 82; 81, 83; 82, identifier:errstr_list; 83, list:[]; 84, comment; 85, expression_statement; 85, 86; 86, assignment; 86, 87; 86, 88; 87, identifier:ex_tag; 88, conditional_expression:if; 88, 89; 88, 90; 88, 91; 89, string:'WARNING'; 90, identifier:iswarning; 91, string:'EXCEPTION'; 92, expression_statement; 92, 93; 93, call; 93, 94; 93, 97; 94, attribute; 94, 95; 94, 96; 95, identifier:errstr_list; 96, identifier:append; 97, argument_list; 97, 98; 98, binary_operator:%; 98, 99; 98, 100; 99, string:'<!!! %s !!!>'; 100, identifier:ex_tag; 101, if_statement; 101, 102; 101, 105; 102, boolean_operator:or; 102, 103; 102, 104; 103, identifier:tb; 104, identifier:FORCE_TB; 105, block; 105, 106; 105, 114; 105, 139; 106, expression_statement; 106, 107; 107, assignment; 107, 108; 107, 109; 108, identifier:tbtext; 109, call; 109, 110; 109, 113; 110, attribute; 110, 111; 110, 112; 111, identifier:traceback; 112, identifier:format_exc; 113, argument_list; 114, if_statement; 114, 115; 114, 118; 115, boolean_operator:or; 115, 116; 115, 117; 116, identifier:colored; 117, identifier:COLORED_EXCEPTIONS; 118, block; 118, 119; 118, 124; 119, import_from_statement; 119, 120; 119, 122; 120, dotted_name; 120, 121; 121, identifier:utool; 122, dotted_name; 122, 123; 123, identifier:util_str; 124, expression_statement; 124, 125; 125, assignment; 125, 126; 125, 127; 126, identifier:tbtext; 127, call; 127, 128; 127, 131; 128, attribute; 128, 129; 128, 130; 129, identifier:util_str; 130, identifier:highlight_text; 131, argument_list; 131, 132; 131, 133; 131, 136; 132, identifier:tbtext; 133, keyword_argument; 133, 134; 133, 135; 134, identifier:lexer_name; 135, string:'pytb'; 136, keyword_argument; 136, 137; 136, 138; 137, identifier:stripall; 138, True; 139, expression_statement; 139, 140; 140, call; 140, 141; 140, 144; 141, attribute; 141, 142; 141, 143; 142, identifier:errstr_list; 143, identifier:append; 144, argument_list; 144, 145; 145, identifier:tbtext; 146, expression_statement; 146, 147; 147, call; 147, 148; 147, 151; 148, attribute; 148, 149; 148, 150; 149, identifier:errstr_list; 150, identifier:append; 151, argument_list; 151, 152; 152, binary_operator:+; 152, 153; 152, 163; 153, binary_operator:+; 153, 154; 153, 157; 154, binary_operator:+; 154, 155; 154, 156; 155, identifier:prefix; 156, string:' '; 157, call; 157, 158; 157, 161; 158, attribute; 158, 159; 158, 160; 159, identifier:six; 160, identifier:text_type; 161, argument_list; 161, 162; 162, identifier:msg; 163, binary_operator:%; 163, 164; 163, 165; 164, string:'\n%r: %s'; 165, tuple; 165, 166; 165, 170; 166, call; 166, 167; 166, 168; 167, identifier:type; 168, argument_list; 168, 169; 169, identifier:ex; 170, call; 170, 171; 170, 174; 171, attribute; 171, 172; 171, 173; 172, identifier:six; 173, identifier:text_type; 174, argument_list; 174, 175; 175, identifier:ex; 176, comment; 177, expression_statement; 177, 178; 178, call; 178, 179; 178, 180; 179, identifier:parse_locals_keylist; 180, argument_list; 180, 181; 180, 182; 180, 183; 180, 184; 181, identifier:locals_; 182, identifier:key_list; 183, identifier:errstr_list; 184, identifier:prefix; 185, expression_statement; 185, 186; 186, call; 186, 187; 186, 190; 187, attribute; 187, 188; 187, 189; 188, identifier:errstr_list; 189, identifier:append; 190, argument_list; 190, 191; 191, binary_operator:%; 191, 192; 191, 193; 192, string:'</!!! %s !!!>'; 193, identifier:ex_tag; 194, return_statement; 194, 195; 195, call; 195, 196; 195, 199; 196, attribute; 196, 197; 196, 198; 197, string:'\n'; 198, identifier:join; 199, argument_list; 199, 200; 200, identifier:errstr_list
def formatex(ex, msg='[!?] Caught exception', prefix=None, key_list=[], locals_=None, iswarning=False, tb=False, N=0, keys=None, colored=None): r""" Formats an exception with relevant info Args: ex (Exception): exception to print msg (unicode): a message to display to the user (default = u'[!?] Caught exception') keys (None): a list of strings denoting variables or expressions of interest (default = []) iswarning (bool): prints as a warning rather than an error if True (default = False) tb (bool): if True prints the traceback in the error message (default = False) prefix (None): (default = None) locals_ (None): (default = None) N (int): (default = 0) colored (None): (default = None) key_list (list): DEPRICATED use keys Returns: str: formated exception CommandLine: python -m utool.util_dbg --exec-formatex Example: >>> # ENABLE_DOCTET >>> from utool.util_dbg import * # NOQA >>> import utool as ut >>> msg = 'Testing Exception' >>> prefix = '[test]' >>> key_list = ['N', 'foo', 'tb'] >>> locals_ = None >>> iswarning = True >>> keys = None >>> colored = None >>> def failfunc(): >>> tb = True >>> N = 0 >>> try: >>> raise Exception('test exception. This is not an error') >>> except Exception as ex: >>> result = formatex(ex, msg, prefix, key_list, locals_, >>> iswarning, tb, N, keys, colored) >>> return result >>> result = failfunc().replace('\n\n', '') >>> print(result) <!!! WARNING !!!> Traceback (most recent call last): File "<string>", line 15, in failfunc Exception: test exception. This is not an error[test] Testing Exception <class 'Exception'>: test exception. This is not an error [test] N = 0 [test] foo = NameError (this likely due to a misformatted printex and is not related to the exception) [test] tb = True </!!! WARNING !!!> """ # Get error prefix and local info if prefix is None: prefix = get_caller_prefix(aserror=True, N=N) if locals_ is None: locals_ = get_parent_frame(N=N).f_locals if keys is not None: # shorthand for key_list key_list = keys # build exception message errstr_list = [] # list of exception strings ex_tag = 'WARNING' if iswarning else 'EXCEPTION' errstr_list.append('<!!! %s !!!>' % ex_tag) if tb or FORCE_TB: tbtext = traceback.format_exc() if colored or COLORED_EXCEPTIONS: from utool import util_str tbtext = util_str.highlight_text(tbtext, lexer_name='pytb', stripall=True) errstr_list.append(tbtext) errstr_list.append(prefix + ' ' + six.text_type(msg) + '\n%r: %s' % (type(ex), six.text_type(ex))) #errstr_list.append(prefix + ' ' + six.text_type(msg) + '\ntype(ex)=%r' % (type(ex),)) parse_locals_keylist(locals_, key_list, errstr_list, prefix) errstr_list.append('</!!! %s !!!>' % ex_tag) return '\n'.join(errstr_list)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 7; 2, function_name:__send_rdy; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:self; 5, identifier:connection; 6, identifier:command; 7, block; 7, 8; 7, 10; 7, 281; 7, 282; 7, 283; 7, 302; 7, 303; 7, 304; 7, 305; 7, 306; 7, 307; 7, 308; 7, 318; 7, 324; 7, 332; 7, 350; 7, 375; 8, expression_statement; 8, 9; 9, comment; 10, if_statement; 10, 11; 10, 18; 10, 225; 11, comparison_operator:is; 11, 12; 11, 17; 12, attribute; 12, 13; 12, 16; 13, attribute; 13, 14; 13, 15; 14, identifier:self; 15, identifier:__consumer; 16, identifier:original_rdy; 17, None; 18, block; 18, 19; 18, 34; 18, 51; 19, expression_statement; 19, 20; 20, assignment; 20, 21; 20, 22; 21, identifier:node_count; 22, call; 22, 23; 22, 28; 23, attribute; 23, 24; 23, 27; 24, attribute; 24, 25; 24, 26; 25, identifier:self; 26, identifier:__consumer; 27, identifier:get_node_count_for_topic; 28, argument_list; 28, 29; 29, attribute; 29, 30; 29, 33; 30, attribute; 30, 31; 30, 32; 31, identifier:connection; 32, identifier:context; 33, identifier:topic; 34, expression_statement; 34, 35; 35, call; 35, 36; 35, 41; 36, attribute; 36, 37; 36, 40; 37, attribute; 37, 38; 37, 39; 38, identifier:self; 39, identifier:__logger_rdy; 40, identifier:debug; 41, argument_list; 41, 42; 41, 45; 41, 50; 42, concatenated_string; 42, 43; 42, 44; 43, string:"Calculating RDY: max_in_flight=(%d) "; 44, string:"node_count=(%d)"; 45, attribute; 45, 46; 45, 49; 46, attribute; 46, 47; 46, 48; 47, identifier:self; 48, identifier:__consumer; 49, identifier:max_in_flight; 50, identifier:node_count; 51, if_statement; 51, 52; 51, 59; 51, 60; 51, 61; 51, 62; 51, 106; 52, comparison_operator:>=; 52, 53; 52, 58; 53, attribute; 53, 54; 53, 57; 54, attribute; 54, 55; 54, 56; 55, identifier:self; 56, identifier:__consumer; 57, identifier:max_in_flight; 58, identifier:node_count; 59, comment; 60, comment; 61, comment; 62, block; 62, 63; 62, 87; 63, expression_statement; 63, 64; 64, assignment; 64, 65; 64, 66; 65, identifier:rdy_this; 66, call; 66, 67; 66, 68; 67, identifier:int; 68, argument_list; 68, 69; 69, call; 69, 70; 69, 73; 70, attribute; 70, 71; 70, 72; 71, identifier:math; 72, identifier:ceil; 73, argument_list; 73, 74; 74, binary_operator:/; 74, 75; 74, 83; 75, call; 75, 76; 75, 77; 76, identifier:float; 77, argument_list; 77, 78; 78, attribute; 78, 79; 78, 82; 79, attribute; 79, 80; 79, 81; 80, identifier:self; 81, identifier:__consumer; 82, identifier:max_in_flight; 83, call; 83, 84; 83, 85; 84, identifier:float; 85, argument_list; 85, 86; 86, identifier:node_count; 87, expression_statement; 87, 88; 88, call; 88, 89; 88, 94; 89, attribute; 89, 90; 89, 93; 90, attribute; 90, 91; 90, 92; 91, identifier:self; 92, identifier:__logger_rdy; 93, identifier:debug; 94, argument_list; 94, 95; 94, 99; 94, 104; 94, 105; 95, concatenated_string; 95, 96; 95, 97; 95, 98; 96, string:"Assigning RDY based on max_in_flight "; 97, string:"(%d) and node count (%d) (optimal): "; 98, string:"(%d)"; 99, attribute; 99, 100; 99, 103; 100, attribute; 100, 101; 100, 102; 101, identifier:self; 102, identifier:__consumer; 103, identifier:max_in_flight; 104, identifier:node_count; 105, identifier:rdy_this; 106, else_clause; 106, 107; 106, 108; 106, 109; 106, 110; 106, 111; 106, 112; 106, 113; 106, 114; 106, 115; 106, 116; 106, 117; 106, 118; 107, comment; 108, comment; 109, comment; 110, comment; 111, comment; 112, comment; 113, comment; 114, comment; 115, comment; 116, comment; 117, comment; 118, block; 118, 119; 118, 130; 118, 157; 118, 167; 118, 221; 119, expression_statement; 119, 120; 120, call; 120, 121; 120, 126; 121, attribute; 121, 122; 121, 125; 122, attribute; 122, 123; 122, 124; 123, identifier:self; 124, identifier:__logger_rdy; 125, identifier:debug; 126, argument_list; 126, 127; 127, concatenated_string; 127, 128; 127, 129; 128, string:"(max_in_flight > nodes). Doing RDY "; 129, string:"election."; 130, expression_statement; 130, 131; 131, assignment; 131, 132; 131, 133; 132, identifier:sleeping_connections; 133, list_comprehension; 133, 134; 133, 135; 133, 136; 133, 150; 133, 151; 134, identifier:c; 135, line_continuation:\; 136, for_in_clause; 136, 137; 136, 140; 136, 141; 137, tuple_pattern; 137, 138; 137, 139; 138, identifier:c; 139, identifier:info; 140, line_continuation:\; 141, call; 141, 142; 141, 149; 142, attribute; 142, 143; 142, 148; 143, attribute; 143, 144; 143, 147; 144, attribute; 144, 145; 144, 146; 145, identifier:self; 146, identifier:__consumer; 147, identifier:connection_context; 148, identifier:items; 149, argument_list; 150, line_continuation:\; 151, if_clause; 151, 152; 152, comparison_operator:==; 152, 153; 152, 156; 153, subscript; 153, 154; 153, 155; 154, identifier:info; 155, string:'rdy_count'; 156, integer:0; 157, expression_statement; 157, 158; 158, call; 158, 159; 158, 164; 159, attribute; 159, 160; 159, 163; 160, attribute; 160, 161; 160, 162; 161, identifier:self; 162, identifier:__logger_rdy; 163, identifier:debug; 164, argument_list; 164, 165; 164, 166; 165, string:"Current sleeping_connections: %s"; 166, identifier:sleeping_connections; 167, if_statement; 167, 168; 167, 169; 167, 207; 168, identifier:sleeping_connections; 169, block; 169, 170; 169, 179; 169, 189; 169, 200; 170, expression_statement; 170, 171; 171, assignment; 171, 172; 171, 173; 172, identifier:elected_connection; 173, call; 173, 174; 173, 177; 174, attribute; 174, 175; 174, 176; 175, identifier:random; 176, identifier:choice; 177, argument_list; 177, 178; 178, identifier:sleeping_connections; 179, expression_statement; 179, 180; 180, call; 180, 181; 180, 186; 181, attribute; 181, 182; 181, 185; 182, attribute; 182, 183; 182, 184; 183, identifier:self; 184, identifier:__logger_rdy; 185, identifier:debug; 186, argument_list; 186, 187; 186, 188; 187, string:"Sending RDY of (1) on: [%s]"; 188, identifier:elected_connection; 189, expression_statement; 189, 190; 190, assignment; 190, 191; 190, 192; 191, identifier:command_elected; 192, call; 192, 193; 192, 198; 193, attribute; 193, 194; 193, 197; 194, attribute; 194, 195; 194, 196; 195, identifier:nsq; 196, identifier:command; 197, identifier:Command; 198, argument_list; 198, 199; 199, identifier:elected_connection; 200, expression_statement; 200, 201; 201, call; 201, 202; 201, 205; 202, attribute; 202, 203; 202, 204; 203, identifier:command_elected; 204, identifier:rdy; 205, argument_list; 205, 206; 206, integer:1; 207, else_clause; 207, 208; 208, block; 208, 209; 209, expression_statement; 209, 210; 210, call; 210, 211; 210, 216; 211, attribute; 211, 212; 211, 215; 212, attribute; 212, 213; 212, 214; 213, identifier:self; 214, identifier:__logger; 215, identifier:debug; 216, argument_list; 216, 217; 216, 220; 217, concatenated_string; 217, 218; 217, 219; 218, string:"No sleeping connections. We got the "; 219, string:"short stick: [%s]"; 220, identifier:connection; 221, expression_statement; 221, 222; 222, assignment; 222, 223; 222, 224; 223, identifier:rdy_this; 224, integer:0; 225, else_clause; 225, 226; 226, block; 226, 227; 227, try_statement; 227, 228; 227, 260; 228, block; 228, 229; 228, 250; 229, expression_statement; 229, 230; 230, assignment; 230, 231; 230, 232; 231, identifier:rdy_this; 232, call; 232, 233; 232, 238; 233, attribute; 233, 234; 233, 237; 234, attribute; 234, 235; 234, 236; 235, identifier:self; 236, identifier:__consumer; 237, identifier:original_rdy; 238, argument_list; 238, 239; 238, 242; 238, 247; 239, attribute; 239, 240; 239, 241; 240, identifier:connection; 241, identifier:node; 242, attribute; 242, 243; 242, 246; 243, attribute; 243, 244; 243, 245; 244, identifier:self; 245, identifier:__consumer; 246, identifier:connection_count; 247, attribute; 247, 248; 247, 249; 248, identifier:self; 249, identifier:__consumer; 250, expression_statement; 250, 251; 251, call; 251, 252; 251, 257; 252, attribute; 252, 253; 252, 256; 253, attribute; 253, 254; 253, 255; 254, identifier:self; 255, identifier:__logger_rdy; 256, identifier:debug; 257, argument_list; 257, 258; 257, 259; 258, string:"Using RDY from callback: (%d)"; 259, identifier:rdy_this; 260, except_clause; 260, 261; 260, 262; 261, identifier:TypeError; 262, block; 262, 263; 262, 271; 263, expression_statement; 263, 264; 264, assignment; 264, 265; 264, 266; 265, identifier:rdy_this; 266, attribute; 266, 267; 266, 270; 267, attribute; 267, 268; 267, 269; 268, identifier:self; 269, identifier:__consumer; 270, identifier:original_rdy; 271, expression_statement; 271, 272; 272, call; 272, 273; 272, 278; 273, attribute; 273, 274; 273, 277; 274, attribute; 274, 275; 274, 276; 275, identifier:self; 276, identifier:__logger_rdy; 277, identifier:debug; 278, argument_list; 278, 279; 278, 280; 279, string:"Using static RDY: (%d)"; 280, identifier:rdy_this; 281, comment; 282, comment; 283, expression_statement; 283, 284; 284, assignment; 284, 285; 284, 286; 285, identifier:rdy_this; 286, call; 286, 287; 286, 288; 287, identifier:min; 288, argument_list; 288, 289; 288, 297; 289, binary_operator:+; 289, 290; 289, 291; 289, 292; 290, identifier:rdy_this; 291, line_continuation:\; 292, call; 292, 293; 292, 296; 293, attribute; 293, 294; 293, 295; 294, identifier:self; 295, identifier:__get_total_rdy_count; 296, argument_list; 297, attribute; 297, 298; 297, 301; 298, attribute; 298, 299; 298, 300; 299, identifier:self; 300, identifier:__consumer; 301, identifier:max_in_flight; 302, comment; 303, comment; 304, comment; 305, comment; 306, comment; 307, comment; 308, expression_statement; 308, 309; 309, assignment; 309, 310; 309, 311; 310, identifier:server_features; 311, attribute; 311, 312; 311, 317; 312, attribute; 312, 313; 312, 316; 313, attribute; 313, 314; 313, 315; 314, identifier:self; 315, identifier:__consumer; 316, identifier:identify; 317, identifier:server_features; 318, expression_statement; 318, 319; 319, assignment; 319, 320; 319, 321; 320, identifier:max_rdy_count; 321, subscript; 321, 322; 321, 323; 322, identifier:server_features; 323, string:'max_rdy_count'; 324, expression_statement; 324, 325; 325, assignment; 325, 326; 325, 327; 326, identifier:rdy_this; 327, call; 327, 328; 327, 329; 328, identifier:min; 329, argument_list; 329, 330; 329, 331; 330, identifier:max_rdy_count; 331, identifier:rdy_this; 332, expression_statement; 332, 333; 333, call; 333, 334; 333, 339; 334, attribute; 334, 335; 334, 338; 335, attribute; 335, 336; 335, 337; 336, identifier:self; 337, identifier:__logger_rdy; 338, identifier:debug; 339, argument_list; 339, 340; 339, 343; 339, 348; 339, 349; 340, concatenated_string; 340, 341; 340, 342; 341, string:"Final RDY (max_in_flight=(%d) "; 342, string:"max_rdy_count=(%d)): (%d)"; 343, attribute; 343, 344; 343, 347; 344, attribute; 344, 345; 344, 346; 345, identifier:self; 346, identifier:__consumer; 347, identifier:max_in_flight; 348, identifier:max_rdy_count; 349, identifier:rdy_this; 350, if_statement; 350, 351; 350, 354; 350, 362; 351, comparison_operator:>; 351, 352; 351, 353; 352, identifier:rdy_this; 353, integer:0; 354, block; 354, 355; 355, expression_statement; 355, 356; 356, call; 356, 357; 356, 360; 357, attribute; 357, 358; 357, 359; 358, identifier:command; 359, identifier:rdy; 360, argument_list; 360, 361; 361, identifier:rdy_this; 362, else_clause; 362, 363; 363, block; 363, 364; 364, expression_statement; 364, 365; 365, call; 365, 366; 365, 371; 366, attribute; 366, 367; 366, 370; 367, attribute; 367, 368; 367, 369; 368, identifier:self; 369, identifier:__logger_rdy; 370, identifier:info; 371, argument_list; 371, 372; 372, concatenated_string; 372, 373; 372, 374; 373, string:"This connection will go to sleep (not "; 374, string:"enough RDY to go around)."; 375, return_statement; 375, 376; 376, identifier:rdy_this
def __send_rdy(self, connection, command): """Determine the RDY value, and set it. It can either be a static value a callback, or None. If it's None, we'll calculate the value based on our limits and connection counts. The documentation recommends starting with (1), but since we are always dealing directly with *nsqd* servers by now, we'll always have a valid count to work with. Since we derive this count off a set of servers that will always be up-to-date, we have everything we need, here, going forward. """ if self.__consumer.original_rdy is None: node_count = self.__consumer.get_node_count_for_topic( connection.context.topic) self.__logger_rdy.debug("Calculating RDY: max_in_flight=(%d) " "node_count=(%d)", self.__consumer.max_in_flight, node_count) if self.__consumer.max_in_flight >= node_count: # Calculate the RDY based on the max_in_flight and total number # of servers. We always round up, or else we'd run the risk of # not facilitating some servers. rdy_this = int(math.ceil( float(self.__consumer.max_in_flight) / float(node_count))) self.__logger_rdy.debug("Assigning RDY based on max_in_flight " "(%d) and node count (%d) (optimal): " "(%d)", self.__consumer.max_in_flight, node_count, rdy_this) else: # We have two possible scenarios: # (1) The client is starting up, and the total RDY count is # already accounted for. # (2) The client is already started, and another connection has # a (0) RDY count. # # In the case of (1), we'll take an RDY of (0). In the case of # (2) We'll send an RDY of (1) on their behalf, before we # assume a (0) for ourself. # Look for existing connections that have a (0) RDY (which # would've only been set to (0) intentionally). self.__logger_rdy.debug("(max_in_flight > nodes). Doing RDY " "election.") sleeping_connections = [ c \ for (c, info) \ in self.__consumer.connection_context.items() \ if info['rdy_count'] == 0] self.__logger_rdy.debug("Current sleeping_connections: %s", sleeping_connections) if sleeping_connections: elected_connection = random.choice(sleeping_connections) self.__logger_rdy.debug("Sending RDY of (1) on: [%s]", elected_connection) command_elected = nsq.command.Command(elected_connection) command_elected.rdy(1) else: self.__logger.debug("No sleeping connections. We got the " "short stick: [%s]", connection) rdy_this = 0 else: try: rdy_this = self.__consumer.original_rdy( connection.node, self.__consumer.connection_count, self.__consumer) self.__logger_rdy.debug("Using RDY from callback: (%d)", rdy_this) except TypeError: rdy_this = self.__consumer.original_rdy self.__logger_rdy.debug("Using static RDY: (%d)", rdy_this) # Make sure that the aggregate set of RDY counts doesn't exceed the # max. This constrains the previous value, above. rdy_this = min(rdy_this + \ self.__get_total_rdy_count(), self.__consumer.max_in_flight) # Make sure we don't exceed the maximum specified by the server. This # only works because we're running greenlets, not threads. At any given # time, only one greenlet is running, and we can make sure to # distribute the remainder of (max_in_flight / nodes) across a subset # of the nodes (they don't all have to have an even slice of # max_in_flight). server_features = self.__consumer.identify.server_features max_rdy_count = server_features['max_rdy_count'] rdy_this = min(max_rdy_count, rdy_this) self.__logger_rdy.debug("Final RDY (max_in_flight=(%d) " "max_rdy_count=(%d)): (%d)", self.__consumer.max_in_flight, max_rdy_count, rdy_this) if rdy_this > 0: command.rdy(rdy_this) else: self.__logger_rdy.info("This connection will go to sleep (not " "enough RDY to go around).") return rdy_this
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:add_instruction; 3, parameters; 3, 4; 3, 5; 4, identifier:self; 5, identifier:instr; 6, block; 6, 7; 6, 9; 6, 16; 6, 25; 6, 54; 7, expression_statement; 7, 8; 8, comment; 9, assert_statement; 9, 10; 10, parenthesized_expression; 10, 11; 11, call; 11, 12; 11, 13; 12, identifier:isinstance; 13, argument_list; 13, 14; 13, 15; 14, identifier:instr; 15, identifier:Instruction; 16, expression_statement; 16, 17; 17, call; 17, 18; 17, 23; 18, attribute; 18, 19; 18, 22; 19, attribute; 19, 20; 19, 21; 20, identifier:self; 21, identifier:instruction_list; 22, identifier:append; 23, argument_list; 23, 24; 24, identifier:instr; 25, if_statement; 25, 26; 25, 33; 26, comparison_operator:not; 26, 27; 26, 30; 27, attribute; 27, 28; 27, 29; 28, identifier:instr; 29, identifier:lhs; 30, attribute; 30, 31; 30, 32; 31, identifier:self; 32, identifier:defined_variables; 33, block; 33, 34; 34, if_statement; 34, 35; 34, 42; 35, call; 35, 36; 35, 37; 36, identifier:isinstance; 37, argument_list; 37, 38; 37, 41; 38, attribute; 38, 39; 38, 40; 39, identifier:instr; 40, identifier:lhs; 41, identifier:Variable; 42, block; 42, 43; 43, expression_statement; 43, 44; 44, call; 44, 45; 44, 50; 45, attribute; 45, 46; 45, 49; 46, attribute; 46, 47; 46, 48; 47, identifier:self; 48, identifier:defined_variables; 49, identifier:append; 50, argument_list; 50, 51; 51, attribute; 51, 52; 51, 53; 52, identifier:instr; 53, identifier:lhs; 54, if_statement; 54, 55; 54, 60; 54, 90; 55, call; 55, 56; 55, 57; 56, identifier:isinstance; 57, argument_list; 57, 58; 57, 59; 58, identifier:instr; 59, identifier:EqInstruction; 60, block; 60, 61; 61, if_statement; 61, 62; 61, 69; 62, call; 62, 63; 62, 64; 63, identifier:isinstance; 64, argument_list; 64, 65; 64, 68; 65, attribute; 65, 66; 65, 67; 66, identifier:instr; 67, identifier:rhs; 68, identifier:Variable; 69, block; 69, 70; 70, if_statement; 70, 71; 70, 78; 71, comparison_operator:not; 71, 72; 71, 75; 72, attribute; 72, 73; 72, 74; 73, identifier:instr; 74, identifier:rhs; 75, attribute; 75, 76; 75, 77; 76, identifier:self; 77, identifier:used_variables; 78, block; 78, 79; 79, expression_statement; 79, 80; 80, call; 80, 81; 80, 86; 81, attribute; 81, 82; 81, 85; 82, attribute; 82, 83; 82, 84; 83, identifier:self; 84, identifier:used_variables; 85, identifier:append; 86, argument_list; 86, 87; 87, attribute; 87, 88; 87, 89; 88, identifier:instr; 89, identifier:rhs; 90, else_clause; 90, 91; 91, block; 91, 92; 91, 121; 92, if_statement; 92, 93; 92, 100; 93, call; 93, 94; 93, 95; 94, identifier:isinstance; 95, argument_list; 95, 96; 95, 99; 96, attribute; 96, 97; 96, 98; 97, identifier:instr; 98, identifier:rhs_1; 99, identifier:Variable; 100, block; 100, 101; 101, if_statement; 101, 102; 101, 109; 102, comparison_operator:not; 102, 103; 102, 106; 103, attribute; 103, 104; 103, 105; 104, identifier:instr; 105, identifier:rhs_1; 106, attribute; 106, 107; 106, 108; 107, identifier:self; 108, identifier:used_variables; 109, block; 109, 110; 110, expression_statement; 110, 111; 111, call; 111, 112; 111, 117; 112, attribute; 112, 113; 112, 116; 113, attribute; 113, 114; 113, 115; 114, identifier:self; 115, identifier:used_variables; 116, identifier:append; 117, argument_list; 117, 118; 118, attribute; 118, 119; 118, 120; 119, identifier:instr; 120, identifier:rhs_1; 121, if_statement; 121, 122; 121, 129; 122, call; 122, 123; 122, 124; 123, identifier:isinstance; 124, argument_list; 124, 125; 124, 128; 125, attribute; 125, 126; 125, 127; 126, identifier:instr; 127, identifier:rhs_2; 128, identifier:Variable; 129, block; 129, 130; 130, if_statement; 130, 131; 130, 138; 131, comparison_operator:not; 131, 132; 131, 135; 132, attribute; 132, 133; 132, 134; 133, identifier:instr; 134, identifier:rhs_2; 135, attribute; 135, 136; 135, 137; 136, identifier:self; 137, identifier:used_variables; 138, block; 138, 139; 139, expression_statement; 139, 140; 140, call; 140, 141; 140, 146; 141, attribute; 141, 142; 141, 145; 142, attribute; 142, 143; 142, 144; 143, identifier:self; 144, identifier:used_variables; 145, identifier:append; 146, argument_list; 146, 147; 147, attribute; 147, 148; 147, 149; 148, identifier:instr; 149, identifier:rhs_2
def add_instruction (self, instr): """ Adds the argument instruction in the list of instructions of this basic block. Also updates the variable lists (used_variables, defined_variables) """ assert(isinstance(instr, Instruction)) self.instruction_list.append(instr) if instr.lhs not in self.defined_variables: if isinstance(instr.lhs, Variable): self.defined_variables.append(instr.lhs) if isinstance(instr, EqInstruction): if isinstance(instr.rhs, Variable): if instr.rhs not in self.used_variables: self.used_variables.append(instr.rhs) else: if isinstance(instr.rhs_1, Variable): if instr.rhs_1 not in self.used_variables: self.used_variables.append(instr.rhs_1) if isinstance(instr.rhs_2, Variable): if instr.rhs_2 not in self.used_variables: self.used_variables.append(instr.rhs_2)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:tokenize; 3, parameters; 3, 4; 4, identifier:self; 5, block; 5, 6; 5, 8; 5, 14; 5, 24; 5, 28; 5, 32; 5, 52; 6, expression_statement; 6, 7; 7, comment; 8, expression_statement; 8, 9; 9, assignment; 9, 10; 9, 13; 10, attribute; 10, 11; 10, 12; 11, identifier:self; 12, identifier:token_list; 13, list:[]; 14, expression_statement; 14, 15; 15, assignment; 15, 16; 15, 17; 16, identifier:ps; 17, call; 17, 18; 17, 23; 18, attribute; 18, 19; 18, 22; 19, attribute; 19, 20; 19, 21; 20, identifier:self; 21, identifier:parse_string; 22, identifier:strip; 23, argument_list; 24, expression_statement; 24, 25; 25, assignment; 25, 26; 25, 27; 26, identifier:i; 27, integer:0; 28, expression_statement; 28, 29; 29, assignment; 29, 30; 29, 31; 30, identifier:last_token; 31, None; 32, while_statement; 32, 33; 32, 47; 33, boolean_operator:and; 33, 34; 33, 40; 34, comparison_operator:<; 34, 35; 34, 36; 35, identifier:i; 36, call; 36, 37; 36, 38; 37, identifier:len; 38, argument_list; 38, 39; 39, identifier:ps; 40, call; 40, 41; 40, 46; 41, attribute; 41, 42; 41, 45; 42, subscript; 42, 43; 42, 44; 43, identifier:ps; 44, identifier:i; 45, identifier:isspace; 46, argument_list; 47, block; 47, 48; 48, expression_statement; 48, 49; 49, augmented_assignment:+=; 49, 50; 49, 51; 50, identifier:i; 51, integer:1; 52, while_statement; 52, 53; 52, 59; 53, comparison_operator:<; 53, 54; 53, 55; 54, identifier:i; 55, call; 55, 56; 55, 57; 56, identifier:len; 57, argument_list; 57, 58; 58, identifier:ps; 59, block; 59, 60; 59, 64; 59, 306; 59, 332; 59, 339; 59, 343; 60, expression_statement; 60, 61; 61, assignment; 61, 62; 61, 63; 62, identifier:token; 63, string:''; 64, if_statement; 64, 65; 64, 72; 64, 106; 64, 208; 64, 294; 65, call; 65, 66; 65, 71; 66, attribute; 66, 67; 66, 70; 67, subscript; 67, 68; 67, 69; 68, identifier:ps; 69, identifier:i; 70, identifier:isalpha; 71, argument_list; 72, block; 72, 73; 73, while_statement; 73, 74; 73, 95; 74, boolean_operator:and; 74, 75; 74, 81; 75, comparison_operator:<; 75, 76; 75, 77; 76, identifier:i; 77, call; 77, 78; 77, 79; 78, identifier:len; 79, argument_list; 79, 80; 80, identifier:ps; 81, parenthesized_expression; 81, 82; 82, boolean_operator:or; 82, 83; 82, 90; 83, call; 83, 84; 83, 89; 84, attribute; 84, 85; 84, 88; 85, subscript; 85, 86; 85, 87; 86, identifier:ps; 87, identifier:i; 88, identifier:isalnum; 89, argument_list; 90, comparison_operator:==; 90, 91; 90, 94; 91, subscript; 91, 92; 91, 93; 92, identifier:ps; 93, identifier:i; 94, string:'_'; 95, block; 95, 96; 95, 102; 96, expression_statement; 96, 97; 97, augmented_assignment:+=; 97, 98; 97, 99; 98, identifier:token; 99, subscript; 99, 100; 99, 101; 100, identifier:ps; 101, identifier:i; 102, expression_statement; 102, 103; 103, augmented_assignment:+=; 103, 104; 103, 105; 104, identifier:i; 105, integer:1; 106, elif_clause; 106, 107; 106, 114; 107, call; 107, 108; 107, 113; 108, attribute; 108, 109; 108, 112; 109, subscript; 109, 110; 109, 111; 110, identifier:ps; 111, identifier:i; 112, identifier:isdigit; 113, argument_list; 114, block; 114, 115; 115, while_statement; 115, 116; 115, 197; 116, boolean_operator:and; 116, 117; 116, 123; 117, comparison_operator:<; 117, 118; 117, 119; 118, identifier:i; 119, call; 119, 120; 119, 121; 120, identifier:len; 121, argument_list; 121, 122; 122, identifier:ps; 123, parenthesized_expression; 123, 124; 124, boolean_operator:or; 124, 125; 124, 174; 125, boolean_operator:or; 125, 126; 125, 151; 126, boolean_operator:or; 126, 127; 126, 146; 127, boolean_operator:or; 127, 128; 127, 141; 128, boolean_operator:or; 128, 129; 128, 136; 129, call; 129, 130; 129, 135; 130, attribute; 130, 131; 130, 134; 131, subscript; 131, 132; 131, 133; 132, identifier:ps; 133, identifier:i; 134, identifier:isdigit; 135, argument_list; 136, comparison_operator:==; 136, 137; 136, 140; 137, subscript; 137, 138; 137, 139; 138, identifier:ps; 139, identifier:i; 140, string:'.'; 141, comparison_operator:==; 141, 142; 141, 145; 142, subscript; 142, 143; 142, 144; 143, identifier:ps; 144, identifier:i; 145, string:'e'; 146, comparison_operator:==; 146, 147; 146, 150; 147, subscript; 147, 148; 147, 149; 148, identifier:ps; 149, identifier:i; 150, string:'E'; 151, parenthesized_expression; 151, 152; 152, boolean_operator:and; 152, 153; 152, 158; 153, comparison_operator:==; 153, 154; 153, 157; 154, subscript; 154, 155; 154, 156; 155, identifier:ps; 156, identifier:i; 157, string:'+'; 158, parenthesized_expression; 158, 159; 159, boolean_operator:or; 159, 160; 159, 167; 160, comparison_operator:==; 160, 161; 160, 166; 161, subscript; 161, 162; 161, 163; 162, identifier:ps; 163, binary_operator:-; 163, 164; 163, 165; 164, identifier:i; 165, integer:1; 166, string:'e'; 167, comparison_operator:==; 167, 168; 167, 173; 168, subscript; 168, 169; 168, 170; 169, identifier:ps; 170, binary_operator:-; 170, 171; 170, 172; 171, identifier:i; 172, integer:1; 173, string:'E'; 174, parenthesized_expression; 174, 175; 175, boolean_operator:and; 175, 176; 175, 181; 176, comparison_operator:==; 176, 177; 176, 180; 177, subscript; 177, 178; 177, 179; 178, identifier:ps; 179, identifier:i; 180, string:'-'; 181, parenthesized_expression; 181, 182; 182, boolean_operator:or; 182, 183; 182, 190; 183, comparison_operator:==; 183, 184; 183, 189; 184, subscript; 184, 185; 184, 186; 185, identifier:ps; 186, binary_operator:-; 186, 187; 186, 188; 187, identifier:i; 188, integer:1; 189, string:'e'; 190, comparison_operator:==; 190, 191; 190, 196; 191, subscript; 191, 192; 191, 193; 192, identifier:ps; 193, binary_operator:-; 193, 194; 193, 195; 194, identifier:i; 195, integer:1; 196, string:'E'; 197, block; 197, 198; 197, 204; 198, expression_statement; 198, 199; 199, augmented_assignment:+=; 199, 200; 199, 201; 200, identifier:token; 201, subscript; 201, 202; 201, 203; 202, identifier:ps; 203, identifier:i; 204, expression_statement; 204, 205; 205, augmented_assignment:+=; 205, 206; 205, 207; 206, identifier:i; 207, integer:1; 208, elif_clause; 208, 209; 208, 214; 209, comparison_operator:==; 209, 210; 209, 213; 210, subscript; 210, 211; 210, 212; 211, identifier:ps; 212, identifier:i; 213, string:'.'; 214, block; 214, 215; 215, if_statement; 215, 216; 215, 225; 215, 259; 216, call; 216, 217; 216, 224; 217, attribute; 217, 218; 217, 223; 218, subscript; 218, 219; 218, 220; 219, identifier:ps; 220, binary_operator:+; 220, 221; 220, 222; 221, identifier:i; 222, integer:1; 223, identifier:isdigit; 224, argument_list; 225, block; 225, 226; 226, while_statement; 226, 227; 226, 248; 227, boolean_operator:and; 227, 228; 227, 234; 228, comparison_operator:<; 228, 229; 228, 230; 229, identifier:i; 230, call; 230, 231; 230, 232; 231, identifier:len; 232, argument_list; 232, 233; 233, identifier:ps; 234, parenthesized_expression; 234, 235; 235, boolean_operator:or; 235, 236; 235, 243; 236, call; 236, 237; 236, 242; 237, attribute; 237, 238; 237, 241; 238, subscript; 238, 239; 238, 240; 239, identifier:ps; 240, identifier:i; 241, identifier:isdigit; 242, argument_list; 243, comparison_operator:==; 243, 244; 243, 247; 244, subscript; 244, 245; 244, 246; 245, identifier:ps; 246, identifier:i; 247, string:'.'; 248, block; 248, 249; 248, 255; 249, expression_statement; 249, 250; 250, augmented_assignment:+=; 250, 251; 250, 252; 251, identifier:token; 252, subscript; 252, 253; 252, 254; 253, identifier:ps; 254, identifier:i; 255, expression_statement; 255, 256; 256, augmented_assignment:+=; 256, 257; 256, 258; 257, identifier:i; 258, integer:1; 259, else_clause; 259, 260; 260, block; 260, 261; 261, while_statement; 261, 262; 261, 283; 262, boolean_operator:and; 262, 263; 262, 269; 263, comparison_operator:<; 263, 264; 263, 265; 264, identifier:i; 265, call; 265, 266; 265, 267; 266, identifier:len; 267, argument_list; 267, 268; 268, identifier:ps; 269, parenthesized_expression; 269, 270; 270, boolean_operator:or; 270, 271; 270, 278; 271, call; 271, 272; 271, 277; 272, attribute; 272, 273; 272, 276; 273, subscript; 273, 274; 273, 275; 274, identifier:ps; 275, identifier:i; 276, identifier:isalpha; 277, argument_list; 278, comparison_operator:==; 278, 279; 278, 282; 279, subscript; 279, 280; 279, 281; 280, identifier:ps; 281, identifier:i; 282, string:'.'; 283, block; 283, 284; 283, 290; 284, expression_statement; 284, 285; 285, augmented_assignment:+=; 285, 286; 285, 287; 286, identifier:token; 287, subscript; 287, 288; 287, 289; 288, identifier:ps; 289, identifier:i; 290, expression_statement; 290, 291; 291, augmented_assignment:+=; 291, 292; 291, 293; 292, identifier:i; 293, integer:1; 294, else_clause; 294, 295; 295, block; 295, 296; 295, 302; 296, expression_statement; 296, 297; 297, augmented_assignment:+=; 297, 298; 297, 299; 298, identifier:token; 299, subscript; 299, 300; 299, 301; 300, identifier:ps; 301, identifier:i; 302, expression_statement; 302, 303; 303, augmented_assignment:+=; 303, 304; 303, 305; 304, identifier:i; 305, integer:1; 306, if_statement; 306, 307; 306, 327; 307, boolean_operator:and; 307, 308; 307, 311; 307, 312; 308, comparison_operator:==; 308, 309; 308, 310; 309, identifier:token; 310, string:'-'; 311, line_continuation:\; 312, parenthesized_expression; 312, 313; 313, boolean_operator:or; 313, 314; 313, 321; 314, boolean_operator:or; 314, 315; 314, 318; 315, comparison_operator:==; 315, 316; 315, 317; 316, identifier:last_token; 317, None; 318, comparison_operator:==; 318, 319; 318, 320; 319, identifier:last_token; 320, string:'('; 321, call; 321, 322; 321, 325; 322, attribute; 322, 323; 322, 324; 323, identifier:self; 324, identifier:is_op; 325, argument_list; 325, 326; 326, identifier:last_token; 327, block; 327, 328; 328, expression_statement; 328, 329; 329, assignment; 329, 330; 329, 331; 330, identifier:token; 331, string:'~'; 332, expression_statement; 332, 333; 333, augmented_assignment:+=; 333, 334; 333, 337; 334, attribute; 334, 335; 334, 336; 335, identifier:self; 336, identifier:token_list; 337, list:[token]; 337, 338; 338, identifier:token; 339, expression_statement; 339, 340; 340, assignment; 340, 341; 340, 342; 341, identifier:last_token; 342, identifier:token; 343, while_statement; 343, 344; 343, 358; 344, boolean_operator:and; 344, 345; 344, 351; 345, comparison_operator:<; 345, 346; 345, 347; 346, identifier:i; 347, call; 347, 348; 347, 349; 348, identifier:len; 349, argument_list; 349, 350; 350, identifier:ps; 351, call; 351, 352; 351, 357; 352, attribute; 352, 353; 352, 356; 353, subscript; 353, 354; 353, 355; 354, identifier:ps; 355, identifier:i; 356, identifier:isspace; 357, argument_list; 358, block; 358, 359; 359, expression_statement; 359, 360; 360, augmented_assignment:+=; 360, 361; 360, 362; 361, identifier:i; 362, integer:1
def tokenize(self): """ Tokenizes the string stored in the parser object into a list of tokens. """ self.token_list = [] ps = self.parse_string.strip() i = 0 last_token = None while i < len(ps) and ps[i].isspace(): i += 1 while i < len(ps): token = '' if ps[i].isalpha(): while i < len(ps) and (ps[i].isalnum() or ps[i] == '_'): token += ps[i] i += 1 elif ps[i].isdigit(): while i < len(ps) and (ps[i].isdigit() or ps[i] == '.' or ps[i] == 'e' or ps[i] == 'E' or (ps[i] == '+' and (ps[i-1] == 'e' or ps[i-1] == 'E')) or (ps[i] == '-' and (ps[i-1] == 'e' or ps[i-1] == 'E'))): token += ps[i] i += 1 elif ps[i] == '.': if ps[i+1].isdigit(): while i < len(ps) and (ps[i].isdigit() or ps[i] == '.'): token += ps[i] i += 1 else: while i < len(ps) and (ps[i].isalpha() or ps[i] == '.'): token += ps[i] i += 1 else: token += ps[i] i += 1 if token == '-' and \ (last_token == None or last_token == '(' or self.is_op(last_token)): token = '~' self.token_list += [token] last_token = token while i < len(ps) and ps[i].isspace(): i += 1
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 4; 2, function_name:setup_repo; 3, parameters; 4, block; 4, 5; 4, 7; 4, 12; 4, 13; 4, 18; 4, 23; 4, 24; 4, 41; 4, 50; 4, 65; 4, 73; 4, 85; 4, 95; 4, 99; 4, 105; 4, 117; 4, 278; 5, expression_statement; 5, 6; 6, comment; 7, expression_statement; 7, 8; 8, call; 8, 9; 8, 10; 9, identifier:print; 10, argument_list; 10, 11; 11, string:'\n [setup_repo]!'; 12, comment; 13, import_from_statement; 13, 14; 13, 16; 14, dotted_name; 14, 15; 15, identifier:functools; 16, dotted_name; 16, 17; 17, identifier:partial; 18, import_statement; 18, 19; 19, aliased_import; 19, 20; 19, 22; 20, dotted_name; 20, 21; 21, identifier:utool; 22, identifier:ut; 23, comment; 24, expression_statement; 24, 25; 25, assignment; 25, 26; 25, 27; 26, identifier:code_dpath; 27, call; 27, 28; 27, 31; 28, attribute; 28, 29; 28, 30; 29, identifier:ut; 30, identifier:truepath; 31, argument_list; 31, 32; 32, call; 32, 33; 32, 36; 33, attribute; 33, 34; 33, 35; 34, identifier:ut; 35, identifier:get_argval; 36, argument_list; 36, 37; 36, 38; 37, string:'--code-dir'; 38, keyword_argument; 38, 39; 38, 40; 39, identifier:default; 40, string:'~/code'; 41, expression_statement; 41, 42; 42, assignment; 42, 43; 42, 44; 43, identifier:_code_dpath; 44, call; 44, 45; 44, 48; 45, attribute; 45, 46; 45, 47; 46, identifier:ut; 47, identifier:unexpanduser; 48, argument_list; 48, 49; 49, identifier:code_dpath; 50, expression_statement; 50, 51; 51, assignment; 51, 52; 51, 53; 52, identifier:repo_fname; 53, parenthesized_expression; 53, 54; 54, call; 54, 55; 54, 58; 55, attribute; 55, 56; 55, 57; 56, identifier:ut; 57, identifier:get_argval; 58, argument_list; 58, 59; 58, 62; 59, tuple; 59, 60; 59, 61; 60, string:'--repo'; 61, string:'--repo-name'; 62, keyword_argument; 62, 63; 62, 64; 63, identifier:type_; 64, identifier:str; 65, expression_statement; 65, 66; 66, assignment; 66, 67; 66, 68; 67, identifier:repo_dpath; 68, call; 68, 69; 68, 70; 69, identifier:join; 70, argument_list; 70, 71; 70, 72; 71, identifier:code_dpath; 72, identifier:repo_fname; 73, expression_statement; 73, 74; 74, assignment; 74, 75; 74, 76; 75, identifier:modname; 76, call; 76, 77; 76, 80; 77, attribute; 77, 78; 77, 79; 78, identifier:ut; 79, identifier:get_argval; 80, argument_list; 80, 81; 80, 82; 81, string:'--modname'; 82, keyword_argument; 82, 83; 82, 84; 83, identifier:default; 84, identifier:repo_fname; 85, expression_statement; 85, 86; 86, call; 86, 87; 86, 90; 87, attribute; 87, 88; 87, 89; 88, identifier:ut; 89, identifier:ensuredir; 90, argument_list; 90, 91; 90, 92; 91, identifier:repo_dpath; 92, keyword_argument; 92, 93; 92, 94; 93, identifier:verbose; 94, True; 95, expression_statement; 95, 96; 96, assignment; 96, 97; 96, 98; 97, identifier:_regencmd; 98, string:'python -m utool --tf setup_repo --repo={repo_fname} --codedir={_code_dpath} --modname={modname}'; 99, expression_statement; 99, 100; 100, assignment; 100, 101; 100, 102; 101, identifier:flake8_noqacmd; 102, binary_operator:+; 102, 103; 102, 104; 103, string:'flake8'; 104, string:':noqa'; 105, expression_statement; 105, 106; 106, assignment; 106, 107; 106, 108; 107, identifier:regencmd; 108, call; 108, 109; 108, 112; 109, attribute; 109, 110; 109, 111; 110, identifier:_regencmd; 111, identifier:format; 112, argument_list; 112, 113; 113, dictionary_splat; 113, 114; 114, call; 114, 115; 114, 116; 115, identifier:locals; 116, argument_list; 117, with_statement; 117, 118; 117, 126; 117, 127; 118, with_clause; 118, 119; 119, with_item; 119, 120; 120, call; 120, 121; 120, 124; 121, attribute; 121, 122; 121, 123; 122, identifier:ut; 123, identifier:ChdirContext; 124, argument_list; 124, 125; 125, identifier:repo_dpath; 126, comment; 127, block; 127, 128; 127, 134; 127, 138; 127, 154; 127, 169; 127, 184; 127, 202; 127, 217; 127, 237; 127, 260; 128, expression_statement; 128, 129; 129, assignment; 129, 130; 129, 131; 130, identifier:locals_; 131, call; 131, 132; 131, 133; 132, identifier:locals; 133, argument_list; 134, expression_statement; 134, 135; 135, assignment; 135, 136; 135, 137; 136, identifier:force; 137, True; 138, expression_statement; 138, 139; 139, assignment; 139, 140; 139, 141; 140, identifier:_ensure_text; 141, call; 141, 142; 141, 143; 142, identifier:partial; 143, argument_list; 143, 144; 143, 145; 143, 148; 143, 151; 144, identifier:ensure_text; 145, keyword_argument; 145, 146; 145, 147; 146, identifier:repo_dpath; 147, string:'.'; 148, keyword_argument; 148, 149; 148, 150; 149, identifier:force; 150, None; 151, keyword_argument; 151, 152; 151, 153; 152, identifier:locals_; 153, identifier:locals_; 154, expression_statement; 154, 155; 155, call; 155, 156; 155, 157; 156, identifier:_ensure_text; 157, argument_list; 157, 158; 157, 161; 158, keyword_argument; 158, 159; 158, 160; 159, identifier:fname; 160, string:'todo.md'; 161, keyword_argument; 161, 162; 161, 163; 162, identifier:text; 163, call; 163, 164; 163, 167; 164, attribute; 164, 165; 164, 166; 165, identifier:ut; 166, identifier:codeblock; 167, argument_list; 167, 168; 168, string:r''' # STARTBLOCK # {modname} TODO File * Add TODOS! # ENDBLOCK '''; 169, expression_statement; 169, 170; 170, call; 170, 171; 170, 172; 171, identifier:_ensure_text; 172, argument_list; 172, 173; 172, 176; 173, keyword_argument; 173, 174; 173, 175; 174, identifier:fname; 175, string:'README.md'; 176, keyword_argument; 176, 177; 176, 178; 177, identifier:text; 178, call; 178, 179; 178, 182; 179, attribute; 179, 180; 179, 181; 180, identifier:ut; 181, identifier:codeblock; 182, argument_list; 182, 183; 183, string:r''' # STARTBLOCK # {modname} README FILE # ENDBLOCK '''; 184, expression_statement; 184, 185; 185, call; 185, 186; 185, 187; 186, identifier:_ensure_text; 187, argument_list; 187, 188; 187, 191; 187, 194; 188, keyword_argument; 188, 189; 188, 190; 189, identifier:fname; 190, string:'setup.py'; 191, keyword_argument; 191, 192; 191, 193; 192, identifier:chmod; 193, string:'+x'; 194, keyword_argument; 194, 195; 194, 196; 195, identifier:text; 196, call; 196, 197; 196, 200; 197, attribute; 197, 198; 197, 199; 198, identifier:ut; 199, identifier:codeblock; 200, argument_list; 200, 201; 201, comment; 202, expression_statement; 202, 203; 203, call; 203, 204; 203, 205; 204, identifier:_ensure_text; 205, argument_list; 205, 206; 205, 209; 206, keyword_argument; 206, 207; 206, 208; 207, identifier:fname; 208, string:'.gitignore'; 209, keyword_argument; 209, 210; 209, 211; 210, identifier:text; 211, call; 211, 212; 211, 215; 212, attribute; 212, 213; 212, 214; 213, identifier:ut; 214, identifier:codeblock; 215, argument_list; 215, 216; 216, string:r''' # STARTBLOCK *.py[cod] # C extensions *.so # Packages *.egg *.egg-info dist build eggs parts bin var sdist develop-eggs .installed.cfg lib lib64 __pycache__ # Installer logs pip-log.txt # Print Logs logs # Unit test / coverage reports .coverage .tox nosetests.xml # Translations *.mo # Mr Developer .mr.developer.cfg .project .pydevproject .DS_Store *.dump.txt *.sqlite3 # profiler *.lprof *.prof *.flann *.npz # utool output _timeings.txt failed.txt *.orig _doc timeings.txt failed_doctests.txt # ENDBLOCK '''; 217, expression_statement; 217, 218; 218, call; 218, 219; 218, 220; 219, identifier:_ensure_text; 220, argument_list; 220, 221; 220, 229; 221, keyword_argument; 221, 222; 221, 223; 222, identifier:fname; 223, call; 223, 224; 223, 225; 224, identifier:join; 225, argument_list; 225, 226; 225, 227; 225, 228; 226, identifier:repo_dpath; 227, identifier:modname; 228, string:'__init__.py'; 229, keyword_argument; 229, 230; 229, 231; 230, identifier:text; 231, call; 231, 232; 231, 235; 232, attribute; 232, 233; 232, 234; 233, identifier:ut; 234, identifier:codeblock; 235, argument_list; 235, 236; 236, comment; 237, expression_statement; 237, 238; 238, call; 238, 239; 238, 240; 239, identifier:_ensure_text; 240, argument_list; 240, 241; 240, 249; 240, 252; 241, keyword_argument; 241, 242; 241, 243; 242, identifier:fname; 243, call; 243, 244; 243, 245; 244, identifier:join; 245, argument_list; 245, 246; 245, 247; 245, 248; 246, identifier:repo_dpath; 247, identifier:modname; 248, string:'__main__.py'; 249, keyword_argument; 249, 250; 249, 251; 250, identifier:chmod; 251, string:'+x'; 252, keyword_argument; 252, 253; 252, 254; 253, identifier:text; 254, call; 254, 255; 254, 258; 255, attribute; 255, 256; 255, 257; 256, identifier:ut; 257, identifier:codeblock; 258, argument_list; 258, 259; 259, comment; 260, expression_statement; 260, 261; 261, call; 261, 262; 261, 263; 262, identifier:_ensure_text; 263, argument_list; 263, 264; 263, 267; 263, 270; 264, keyword_argument; 264, 265; 264, 266; 265, identifier:fname; 266, string:'run_tests.py'; 267, keyword_argument; 267, 268; 267, 269; 268, identifier:chmod; 269, string:'+x'; 270, keyword_argument; 270, 271; 270, 272; 271, identifier:text; 272, call; 272, 273; 272, 276; 273, attribute; 273, 274; 273, 275; 274, identifier:ut; 275, identifier:codeblock; 276, argument_list; 276, 277; 277, comment; 278, expression_statement; 278, 279; 279, call; 279, 280; 279, 283; 280, attribute; 280, 281; 280, 282; 281, identifier:ut; 282, identifier:ensuredir; 283, argument_list; 283, 284; 283, 289; 284, call; 284, 285; 284, 286; 285, identifier:join; 286, argument_list; 286, 287; 286, 288; 287, identifier:repo_dpath; 288, identifier:modname; 289, keyword_argument; 289, 290; 289, 291; 290, identifier:verbose; 291, True
def setup_repo(): r""" Creates default structure for a new repo CommandLine: python -m utool setup_repo --repo=dtool --codedir=~/code python -m utool setup_repo --repo=dtool --codedir=~/code python -m utool setup_repo --repo=ibeis-flukematch-module --codedir=~/code --modname=ibeis_flukematch python -m utool setup_repo --repo=mtgmonte --codedir=~/code --modname=mtgmonte python -m utool setup_repo --repo=pydarknet --codedir=~/code --modname=pydarknet python -m utool setup_repo --repo=sandbox_utools --codedir=~/code --modname=sandbox_utools python -m utool setup_repo --repo=ubelt --codedir=~/code --modname=ubelt -w python -m utool setup_repo Python: ipython import utool as ut ut.rrrr(0); ut.setup_repo() Example: >>> # DISABLE_DOCTEST >>> # SCRIPT >>> from utool.util_project import * # NOQA >>> import utool as ut >>> result = setup_repo() >>> print(result) """ print('\n [setup_repo]!') # import os from functools import partial import utool as ut # import os code_dpath = ut.truepath(ut.get_argval('--code-dir', default='~/code')) _code_dpath = ut.unexpanduser(code_dpath) repo_fname = (ut.get_argval(('--repo', '--repo-name'), type_=str)) repo_dpath = join(code_dpath, repo_fname) modname = ut.get_argval('--modname', default=repo_fname) ut.ensuredir(repo_dpath, verbose=True) _regencmd = 'python -m utool --tf setup_repo --repo={repo_fname} --codedir={_code_dpath} --modname={modname}' flake8_noqacmd = 'flake8' + ':noqa' regencmd = _regencmd.format(**locals()) with ut.ChdirContext(repo_dpath): # os.chdir(repo_fname) locals_ = locals() force = True _ensure_text = partial(ensure_text, repo_dpath='.', force=None, locals_=locals_) _ensure_text( fname='todo.md', text=ut.codeblock( r''' # STARTBLOCK # {modname} TODO File * Add TODOS! # ENDBLOCK ''') ) _ensure_text( fname='README.md', text=ut.codeblock( r''' # STARTBLOCK # {modname} README FILE # ENDBLOCK ''') ) _ensure_text( fname='setup.py', chmod='+x', text=ut.codeblock( r''' # STARTBLOCK #!/usr/bin/env python """ Initially Generated By: {regencmd} --force-{fname} """ from __future__ import absolute_import, division, print_function, unicode_literals from setuptools import setup try: from utool import util_setup except ImportError: print('ERROR: setup requires utool') raise INSTALL_REQUIRES = [ #'cython >= 0.21.1', #'numpy >= 1.9.0', #'scipy >= 0.16.0', ] CLUTTER_PATTERNS = [ # Patterns removed by python setup.py clean ] if __name__ == '__main__': kwargs = util_setup.setuptools_setup( setup_fpath=__file__, name='{modname}', packages=util_setup.find_packages(), version=util_setup.parse_package_for_version('{modname}'), license=util_setup.read_license('LICENSE'), long_description=util_setup.parse_readme('README.md'), ext_modules=util_setup.find_ext_modules(), cmdclass=util_setup.get_cmdclass(), #description='description of module', #url='https://github.com/<username>/{repo_fname}.git', #author='<author>', #author_email='<author_email>', keywords='', install_requires=INSTALL_REQUIRES, clutter_patterns=CLUTTER_PATTERNS, #package_data={{'build': ut.get_dynamic_lib_globstrs()}}, #build_command=lambda: ut.std_build_command(dirname(__file__)), classifiers=[], ) setup(**kwargs) # ENDBLOCK ''' ) ) _ensure_text( fname='.gitignore', text=ut.codeblock( r''' # STARTBLOCK *.py[cod] # C extensions *.so # Packages *.egg *.egg-info dist build eggs parts bin var sdist develop-eggs .installed.cfg lib lib64 __pycache__ # Installer logs pip-log.txt # Print Logs logs # Unit test / coverage reports .coverage .tox nosetests.xml # Translations *.mo # Mr Developer .mr.developer.cfg .project .pydevproject .DS_Store *.dump.txt *.sqlite3 # profiler *.lprof *.prof *.flann *.npz # utool output _timeings.txt failed.txt *.orig _doc timeings.txt failed_doctests.txt # ENDBLOCK ''' ) ) _ensure_text( fname=join(repo_dpath, modname, '__init__.py'), text=ut.codeblock( r''' # STARTBLOCK # -*- coding: utf-8 -*- # {flake8_noqacmd} """ Initially Generated By: {regencmd} """ from __future__ import absolute_import, division, print_function, unicode_literals import sys __version__ = '0.0.0' IMPORT_TUPLES = [ # ('<modname>', None), ] __DYNAMIC__ = '--nodyn' not in sys.argv """ python -c "import {modname}" --dump-{modname}-init python -c "import {modname}" --update-{modname}-init """ DOELSE = False if __DYNAMIC__: # Dynamically import listed util libraries and their members. from utool._internal import util_importer ignore_endswith = [] import_execstr = util_importer.dynamic_import( __name__, IMPORT_TUPLES, ignore_endswith=ignore_endswith) exec(import_execstr) DOELSE = False else: DOELSE = True if DOELSE: # <AUTOGEN_INIT> pass # </AUTOGEN_INIT> # ENDBLOCK ''' ) ) _ensure_text( fname=join(repo_dpath, modname, '__main__.py'), chmod='+x', text=ut.codeblock( r''' # STARTBLOCK #!/usr/bin/env python # -*- coding: utf-8 -*- """ Initially Generated By: {regencmd} """ from __future__ import absolute_import, division, print_function, unicode_literals def {modname}_main(): ignore_prefix = [] ignore_suffix = [] import utool as ut ut.main_function_tester('{modname}', ignore_prefix, ignore_suffix) if __name__ == '__main__': """ Usage: python -m {modname} <funcname> """ print('Running {modname} main') {modname}_main() # ENDBLOCK ''' ) ) _ensure_text( fname='run_tests.py', chmod='+x', text=ut.codeblock( r''' # STARTBLOCK #!/usr/bin/env python """ Initially Generated By: {regencmd} --force-{fname} """ from __future__ import absolute_import, division, print_function import sys import utool as ut def run_tests(): # Build module list and run tests import sys ut.change_term_title('RUN {modname} TESTS') exclude_doctests_fnames = set([ ]) exclude_dirs = [ '_broken', 'old', 'tests', 'timeits', '_scripts', '_timeits', '_doc', 'notebook', ] dpath_list = ['{modname}'] doctest_modname_list = ut.find_doctestable_modnames( dpath_list, exclude_doctests_fnames, exclude_dirs) coverage = ut.get_argflag(('--coverage', '--cov',)) if coverage: import coverage cov = coverage.Coverage(source=doctest_modname_list) cov.start() print('Starting coverage') exclude_lines = [ 'pragma: no cover', 'def __repr__', 'if self.debug:', 'if settings.DEBUG', 'raise AssertionError', 'raise NotImplementedError', 'if 0:', 'if ut.VERBOSE', 'if _debug:', 'if __name__ == .__main__.:', 'print(.*)', ] for line in exclude_lines: cov.exclude(line) for modname in doctest_modname_list: exec('import ' + modname, globals()) module_list = [sys.modules[name] for name in doctest_modname_list] nPass, nTotal, failed_cmd_list = ut.doctest_module_list(module_list) if coverage: print('Stoping coverage') cov.stop() print('Saving coverage') cov.save() print('Generating coverage html report') cov.html_report() if nPass != nTotal: return 1 else: return 0 if __name__ == '__main__': import multiprocessing multiprocessing.freeze_support() retcode = run_tests() sys.exit(retcode) # ENDBLOCK ''' ) ) ut.ensuredir(join(repo_dpath, modname), verbose=True)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 36; 2, function_name:generate2; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 3, 12; 3, 15; 3, 18; 3, 21; 3, 24; 3, 27; 3, 30; 3, 33; 4, identifier:func; 5, identifier:args_gen; 6, default_parameter; 6, 7; 6, 8; 7, identifier:kw_gen; 8, None; 9, default_parameter; 9, 10; 9, 11; 10, identifier:ntasks; 11, None; 12, default_parameter; 12, 13; 12, 14; 13, identifier:ordered; 14, True; 15, default_parameter; 15, 16; 15, 17; 16, identifier:force_serial; 17, False; 18, default_parameter; 18, 19; 18, 20; 19, identifier:use_pool; 20, False; 21, default_parameter; 21, 22; 21, 23; 22, identifier:chunksize; 23, None; 24, default_parameter; 24, 25; 24, 26; 25, identifier:nprocs; 26, None; 27, default_parameter; 27, 28; 27, 29; 28, identifier:progkw; 29, dictionary; 30, default_parameter; 30, 31; 30, 32; 31, identifier:nTasks; 32, None; 33, default_parameter; 33, 34; 33, 35; 34, identifier:verbose; 35, None; 36, block; 36, 37; 36, 39; 36, 48; 36, 57; 36, 89; 36, 102; 36, 109; 36, 124; 36, 139; 36, 148; 36, 160; 36, 175; 37, expression_statement; 37, 38; 38, comment; 39, if_statement; 39, 40; 39, 43; 40, comparison_operator:is; 40, 41; 40, 42; 41, identifier:verbose; 42, None; 43, block; 43, 44; 44, expression_statement; 44, 45; 45, assignment; 45, 46; 45, 47; 46, identifier:verbose; 47, integer:2; 48, if_statement; 48, 49; 48, 52; 49, comparison_operator:is; 49, 50; 49, 51; 50, identifier:ntasks; 51, None; 52, block; 52, 53; 53, expression_statement; 53, 54; 54, assignment; 54, 55; 54, 56; 55, identifier:ntasks; 56, identifier:nTasks; 57, if_statement; 57, 58; 57, 61; 58, comparison_operator:is; 58, 59; 58, 60; 59, identifier:ntasks; 60, None; 61, block; 61, 62; 62, try_statement; 62, 63; 62, 71; 63, block; 63, 64; 64, expression_statement; 64, 65; 65, assignment; 65, 66; 65, 67; 66, identifier:ntasks; 67, call; 67, 68; 67, 69; 68, identifier:len; 69, argument_list; 69, 70; 70, identifier:args_gen; 71, except_clause; 71, 72; 71, 73; 71, 74; 72, identifier:TypeError; 73, comment; 74, block; 74, 75; 74, 82; 75, expression_statement; 75, 76; 76, assignment; 76, 77; 76, 78; 77, identifier:args_gen; 78, call; 78, 79; 78, 80; 79, identifier:list; 80, argument_list; 80, 81; 81, identifier:args_gen; 82, expression_statement; 82, 83; 83, assignment; 83, 84; 83, 85; 84, identifier:ntasks; 85, call; 85, 86; 85, 87; 86, identifier:len; 87, argument_list; 87, 88; 88, identifier:args_gen; 89, if_statement; 89, 90; 89, 97; 90, boolean_operator:or; 90, 91; 90, 94; 91, comparison_operator:==; 91, 92; 91, 93; 92, identifier:ntasks; 93, integer:1; 94, comparison_operator:<; 94, 95; 94, 96; 95, identifier:ntasks; 96, identifier:__MIN_PARALLEL_TASKS__; 97, block; 97, 98; 98, expression_statement; 98, 99; 99, assignment; 99, 100; 99, 101; 100, identifier:force_serial; 101, True; 102, if_statement; 102, 103; 102, 104; 103, identifier:__FORCE_SERIAL__; 104, block; 104, 105; 105, expression_statement; 105, 106; 106, assignment; 106, 107; 106, 108; 107, identifier:force_serial; 108, identifier:__FORCE_SERIAL__; 109, if_statement; 109, 110; 109, 113; 110, comparison_operator:==; 110, 111; 110, 112; 111, identifier:ntasks; 112, integer:0; 113, block; 113, 114; 113, 122; 114, if_statement; 114, 115; 114, 116; 115, identifier:verbose; 116, block; 116, 117; 117, expression_statement; 117, 118; 118, call; 118, 119; 118, 120; 119, identifier:print; 120, argument_list; 120, 121; 121, string:'[ut.generate2] submitted 0 tasks'; 122, raise_statement; 122, 123; 123, identifier:StopIteration; 124, if_statement; 124, 125; 124, 128; 125, comparison_operator:is; 125, 126; 125, 127; 126, identifier:nprocs; 127, None; 128, block; 128, 129; 129, expression_statement; 129, 130; 130, assignment; 130, 131; 130, 132; 131, identifier:nprocs; 132, call; 132, 133; 132, 134; 133, identifier:min; 134, argument_list; 134, 135; 134, 136; 135, identifier:ntasks; 136, call; 136, 137; 136, 138; 137, identifier:get_default_numprocs; 138, argument_list; 139, if_statement; 139, 140; 139, 143; 140, comparison_operator:==; 140, 141; 140, 142; 141, identifier:nprocs; 142, integer:1; 143, block; 143, 144; 144, expression_statement; 144, 145; 145, assignment; 145, 146; 145, 147; 146, identifier:force_serial; 147, True; 148, if_statement; 148, 149; 148, 152; 149, comparison_operator:is; 149, 150; 149, 151; 150, identifier:kw_gen; 151, None; 152, block; 152, 153; 153, expression_statement; 153, 154; 154, assignment; 154, 155; 154, 156; 155, identifier:kw_gen; 156, binary_operator:*; 156, 157; 156, 159; 157, list:[{}]; 157, 158; 158, dictionary; 159, identifier:ntasks; 160, if_statement; 160, 161; 160, 166; 160, 167; 161, call; 161, 162; 161, 163; 162, identifier:isinstance; 163, argument_list; 163, 164; 163, 165; 164, identifier:kw_gen; 165, identifier:dict; 166, comment; 167, block; 167, 168; 168, expression_statement; 168, 169; 169, assignment; 169, 170; 169, 171; 170, identifier:kw_gen; 171, binary_operator:*; 171, 172; 171, 174; 172, list:[kw_gen]; 172, 173; 173, identifier:kw_gen; 174, identifier:ntasks; 175, if_statement; 175, 176; 175, 177; 175, 199; 176, identifier:force_serial; 177, block; 177, 178; 178, for_statement; 178, 179; 178, 180; 178, 195; 179, identifier:result; 180, call; 180, 181; 180, 182; 181, identifier:_generate_serial2; 182, argument_list; 182, 183; 182, 184; 182, 185; 182, 186; 182, 189; 182, 192; 183, identifier:func; 184, identifier:args_gen; 185, identifier:kw_gen; 186, keyword_argument; 186, 187; 186, 188; 187, identifier:ntasks; 188, identifier:ntasks; 189, keyword_argument; 189, 190; 189, 191; 190, identifier:progkw; 191, identifier:progkw; 192, keyword_argument; 192, 193; 192, 194; 193, identifier:verbose; 194, identifier:verbose; 195, block; 195, 196; 196, expression_statement; 196, 197; 197, yield; 197, 198; 198, identifier:result; 199, else_clause; 199, 200; 200, block; 200, 201; 200, 231; 200, 288; 201, if_statement; 201, 202; 201, 203; 202, identifier:verbose; 203, block; 203, 204; 203, 211; 203, 215; 204, expression_statement; 204, 205; 205, assignment; 205, 206; 205, 207; 206, identifier:gentype; 207, conditional_expression:if; 207, 208; 207, 209; 207, 210; 208, string:'mp'; 209, identifier:use_pool; 210, string:'futures'; 211, expression_statement; 211, 212; 212, assignment; 212, 213; 212, 214; 213, identifier:fmtstr; 214, string:'[generate2] executing {} {} tasks using {} {} procs'; 215, expression_statement; 215, 216; 216, call; 216, 217; 216, 218; 217, identifier:print; 218, argument_list; 218, 219; 219, call; 219, 220; 219, 223; 220, attribute; 220, 221; 220, 222; 221, identifier:fmtstr; 222, identifier:format; 223, argument_list; 223, 224; 223, 225; 223, 229; 223, 230; 224, identifier:ntasks; 225, call; 225, 226; 225, 227; 226, identifier:get_funcname; 227, argument_list; 227, 228; 228, identifier:func; 229, identifier:nprocs; 230, identifier:gentype; 231, if_statement; 231, 232; 231, 235; 232, comparison_operator:>; 232, 233; 232, 234; 233, identifier:verbose; 234, integer:1; 235, block; 235, 236; 235, 246; 235, 264; 235, 271; 235, 272; 236, expression_statement; 236, 237; 237, assignment; 237, 238; 237, 239; 238, identifier:lbl; 239, binary_operator:%; 239, 240; 239, 241; 240, string:'(pargen) %s: '; 241, tuple; 241, 242; 242, call; 242, 243; 242, 244; 243, identifier:get_funcname; 244, argument_list; 244, 245; 245, identifier:func; 246, expression_statement; 246, 247; 247, assignment; 247, 248; 247, 249; 248, identifier:progkw_; 249, call; 249, 250; 249, 251; 250, identifier:dict; 251, argument_list; 251, 252; 251, 255; 251, 258; 251, 261; 252, keyword_argument; 252, 253; 252, 254; 253, identifier:freq; 254, None; 255, keyword_argument; 255, 256; 255, 257; 256, identifier:bs; 257, True; 258, keyword_argument; 258, 259; 258, 260; 259, identifier:adjust; 260, False; 261, keyword_argument; 261, 262; 261, 263; 262, identifier:freq_est; 263, string:'absolute'; 264, expression_statement; 264, 265; 265, call; 265, 266; 265, 269; 266, attribute; 266, 267; 266, 268; 267, identifier:progkw_; 268, identifier:update; 269, argument_list; 269, 270; 270, identifier:progkw; 271, comment; 272, expression_statement; 272, 273; 273, assignment; 273, 274; 273, 275; 274, identifier:progpart; 275, call; 275, 276; 275, 279; 276, attribute; 276, 277; 276, 278; 277, identifier:util_progress; 278, identifier:ProgPartial; 279, argument_list; 279, 280; 279, 283; 279, 286; 280, keyword_argument; 280, 281; 280, 282; 281, identifier:length; 282, identifier:ntasks; 283, keyword_argument; 283, 284; 283, 285; 284, identifier:lbl; 285, identifier:lbl; 286, dictionary_splat; 286, 287; 287, identifier:progkw_; 288, if_statement; 288, 289; 288, 290; 288, 291; 288, 403; 289, identifier:use_pool; 290, comment; 291, block; 291, 292; 291, 318; 292, if_statement; 292, 293; 292, 296; 293, comparison_operator:is; 293, 294; 293, 295; 294, identifier:chunksize; 295, None; 296, block; 296, 297; 297, expression_statement; 297, 298; 298, assignment; 298, 299; 298, 300; 299, identifier:chunksize; 300, call; 300, 301; 300, 302; 301, identifier:max; 302, argument_list; 302, 303; 302, 308; 303, call; 303, 304; 303, 305; 304, identifier:min; 305, argument_list; 305, 306; 305, 307; 306, integer:4; 307, identifier:ntasks; 308, call; 308, 309; 308, 310; 309, identifier:min; 310, argument_list; 310, 311; 310, 312; 311, integer:8; 312, binary_operator://; 312, 313; 312, 314; 313, identifier:ntasks; 314, parenthesized_expression; 314, 315; 315, binary_operator:**; 315, 316; 315, 317; 316, identifier:nprocs; 317, integer:2; 318, try_statement; 318, 319; 318, 389; 319, block; 319, 320; 319, 329; 319, 346; 319, 361; 319, 370; 319, 382; 320, expression_statement; 320, 321; 321, assignment; 321, 322; 321, 323; 322, identifier:pool; 323, call; 323, 324; 323, 327; 324, attribute; 324, 325; 324, 326; 325, identifier:multiprocessing; 326, identifier:Pool; 327, argument_list; 327, 328; 328, identifier:nprocs; 329, if_statement; 329, 330; 329, 331; 329, 338; 330, identifier:ordered; 331, block; 331, 332; 332, expression_statement; 332, 333; 333, assignment; 333, 334; 333, 335; 334, identifier:pmap_func; 335, attribute; 335, 336; 335, 337; 336, identifier:pool; 337, identifier:imap; 338, else_clause; 338, 339; 339, block; 339, 340; 340, expression_statement; 340, 341; 341, assignment; 341, 342; 341, 343; 342, identifier:pmap_func; 343, attribute; 343, 344; 343, 345; 344, identifier:pool; 345, identifier:imap_unordered; 346, expression_statement; 346, 347; 347, assignment; 347, 348; 347, 349; 348, identifier:wrapped_arg_gen; 349, call; 349, 350; 349, 351; 350, identifier:zip; 351, argument_list; 351, 352; 351, 359; 351, 360; 352, binary_operator:*; 352, 353; 352, 355; 353, list:[func]; 353, 354; 354, identifier:func; 355, call; 355, 356; 355, 357; 356, identifier:len; 357, argument_list; 357, 358; 358, identifier:args_gen; 359, identifier:args_gen; 360, identifier:kw_gen; 361, expression_statement; 361, 362; 362, assignment; 362, 363; 362, 364; 363, identifier:res_gen; 364, call; 364, 365; 364, 366; 365, identifier:pmap_func; 366, argument_list; 366, 367; 366, 368; 366, 369; 367, identifier:_kw_wrap_worker; 368, identifier:wrapped_arg_gen; 369, identifier:chunksize; 370, if_statement; 370, 371; 370, 374; 371, comparison_operator:>; 371, 372; 371, 373; 372, identifier:verbose; 373, integer:1; 374, block; 374, 375; 375, expression_statement; 375, 376; 376, assignment; 376, 377; 376, 378; 377, identifier:res_gen; 378, call; 378, 379; 378, 380; 379, identifier:progpart; 380, argument_list; 380, 381; 381, identifier:res_gen; 382, for_statement; 382, 383; 382, 384; 382, 385; 383, identifier:res; 384, identifier:res_gen; 385, block; 385, 386; 386, expression_statement; 386, 387; 387, yield; 387, 388; 388, identifier:res; 389, finally_clause; 389, 390; 390, block; 390, 391; 390, 397; 391, expression_statement; 391, 392; 392, call; 392, 393; 392, 396; 393, attribute; 393, 394; 393, 395; 394, identifier:pool; 395, identifier:close; 396, argument_list; 397, expression_statement; 397, 398; 398, call; 398, 399; 398, 402; 399, attribute; 399, 400; 399, 401; 400, identifier:pool; 401, identifier:join; 402, argument_list; 403, else_clause; 403, 404; 403, 405; 404, comment; 405, block; 405, 406; 405, 415; 406, expression_statement; 406, 407; 407, assignment; 407, 408; 407, 409; 408, identifier:executor; 409, call; 409, 410; 409, 413; 410, attribute; 410, 411; 410, 412; 411, identifier:futures; 412, identifier:ProcessPoolExecutor; 413, argument_list; 413, 414; 414, identifier:nprocs; 415, try_statement; 415, 416; 415, 480; 416, block; 416, 417; 416, 440; 416, 444; 416, 457; 416, 469; 417, expression_statement; 417, 418; 418, assignment; 418, 419; 418, 420; 419, identifier:fs_list; 420, list_comprehension; 420, 421; 420, 431; 421, call; 421, 422; 421, 425; 422, attribute; 422, 423; 422, 424; 423, identifier:executor; 424, identifier:submit; 425, argument_list; 425, 426; 425, 427; 425, 429; 426, identifier:func; 427, list_splat; 427, 428; 428, identifier:a; 429, dictionary_splat; 429, 430; 430, identifier:k; 431, for_in_clause; 431, 432; 431, 435; 432, pattern_list; 432, 433; 432, 434; 433, identifier:a; 434, identifier:k; 435, call; 435, 436; 435, 437; 436, identifier:zip; 437, argument_list; 437, 438; 437, 439; 438, identifier:args_gen; 439, identifier:kw_gen; 440, expression_statement; 440, 441; 441, assignment; 441, 442; 441, 443; 442, identifier:fs_gen; 443, identifier:fs_list; 444, if_statement; 444, 445; 444, 447; 445, not_operator; 445, 446; 446, identifier:ordered; 447, block; 447, 448; 448, expression_statement; 448, 449; 449, assignment; 449, 450; 449, 451; 450, identifier:fs_gen; 451, call; 451, 452; 451, 455; 452, attribute; 452, 453; 452, 454; 453, identifier:futures; 454, identifier:as_completed; 455, argument_list; 455, 456; 456, identifier:fs_gen; 457, if_statement; 457, 458; 457, 461; 458, comparison_operator:>; 458, 459; 458, 460; 459, identifier:verbose; 460, integer:1; 461, block; 461, 462; 462, expression_statement; 462, 463; 463, assignment; 463, 464; 463, 465; 464, identifier:fs_gen; 465, call; 465, 466; 465, 467; 466, identifier:progpart; 467, argument_list; 467, 468; 468, identifier:fs_gen; 469, for_statement; 469, 470; 469, 471; 469, 472; 470, identifier:fs; 471, identifier:fs_gen; 472, block; 472, 473; 473, expression_statement; 473, 474; 474, yield; 474, 475; 475, call; 475, 476; 475, 479; 476, attribute; 476, 477; 476, 478; 477, identifier:fs; 478, identifier:result; 479, argument_list; 480, finally_clause; 480, 481; 481, block; 481, 482; 482, expression_statement; 482, 483; 483, call; 483, 484; 483, 487; 484, attribute; 484, 485; 484, 486; 485, identifier:executor; 486, identifier:shutdown; 487, argument_list; 487, 488; 488, keyword_argument; 488, 489; 488, 490; 489, identifier:wait; 490, True
def generate2(func, args_gen, kw_gen=None, ntasks=None, ordered=True, force_serial=False, use_pool=False, chunksize=None, nprocs=None, progkw={}, nTasks=None, verbose=None): r""" Interfaces to either multiprocessing or futures. Esentially maps ``args_gen`` onto ``func`` using pool.imap. However, args_gen must be a tuple of args that will be unpacked and send to the function. Thus, the function can take multiple args. Also specifing keyword args is supported. Useful for embarrassingly parallel loops. Currently does not work with opencv3 CommandLine: python -m utool.util_parallel generate2 Args: func (function): live python function args_gen (?): kw_gen (None): (default = None) ntasks (None): (default = None) ordered (bool): (default = True) force_serial (bool): (default = False) verbose (bool): verbosity flag(default = None) CommandLine: python -m utool.util_parallel generate2 Example: >>> # DISABLE_DOCTEST >>> from utool.util_parallel import * # NOQA >>> from utool.util_parallel import _kw_wrap_worker # NOQA >>> import utool as ut >>> args_gen = list(zip(range(10000))) >>> kw_gen = [{}] * len(args_gen) >>> func = ut.is_prime >>> _ = list(generate2(func, args_gen)) >>> _ = list(generate2(func, args_gen, ordered=False)) >>> _ = list(generate2(func, args_gen, force_serial=True)) >>> _ = list(generate2(func, args_gen, use_pool=True)) >>> _ = list(generate2(func, args_gen, ordered=False, verbose=False)) Example0: >>> # ENABLE_DOCTEST >>> import utool as ut >>> #num = 8700 # parallel is slower for smaller numbers >>> num = 500 # parallel has an initial (~.1 second startup overhead) >>> print('TESTING SERIAL') >>> func = ut.is_prime >>> args_list = list(range(0, num)) >>> flag_generator0 = ut.generate2(ut.is_prime, zip(range(0, num)), force_serial=True) >>> flag_list0 = list(flag_generator0) >>> print('TESTING PARALLEL') >>> flag_generator1 = ut.generate2(ut.is_prime, zip(range(0, num))) >>> flag_list1 = list(flag_generator1) >>> print('ASSERTING') >>> assert len(flag_list1) == num >>> assert flag_list0 == flag_list1 Example1: >>> # ENABLE_DOCTEST >>> # Trying to recreate the freeze seen in IBEIS >>> import utool as ut >>> print('TESTING SERIAL') >>> flag_generator0 = ut.generate2(ut.is_prime, zip(range(0, 1))) >>> flag_list0 = list(flag_generator0) >>> flag_generator1 = ut.generate2(ut.fibonacci_recursive, zip(range(0, 1))) >>> flag_list1 = list(flag_generator1) >>> print('TESTING PARALLEL') >>> flag_generator2 = ut.generate2(ut.is_prime, zip(range(0, 12))) >>> flag_list2 = list(flag_generator2) >>> flag_generator3 = ut.generate2(ut.fibonacci_recursive, zip(range(0, 12))) >>> flag_list3 = list(flag_generator3) >>> print('flag_list0 = %r' % (flag_list0,)) >>> print('flag_list1 = %r' % (flag_list1,)) >>> print('flag_list2 = %r' % (flag_list1,)) >>> print('flag_list3 = %r' % (flag_list1,)) Example2: >>> # DISABLE_DOCTEST >>> # UNSTABLE_DOCTEST >>> # Trying to recreate the freeze seen in IBEIS >>> import vtool as vt >>> #def gen_chip(tup): >>> # import vtool as vt >>> # cfpath, gfpath, bbox, theta, new_size, filter_list = tup >>> # chipBGR = vt.compute_chip(gfpath, bbox, theta, new_size, filter_list) >>> # height, width = chipBGR.shape[0:2] >>> # vt.imwrite(cfpath, chipBGR) >>> # return cfpath, width, height >>> import utool as ut >>> from ibeis.algo.preproc.preproc_chip import gen_chip >>> #from ibeis.algo.preproc.preproc_feat import gen_feat_worker >>> key_list = ['grace.jpg', 'easy1.png', 'ada2.jpg', 'easy3.png', >>> 'hard3.png', 'zebra.png', 'patsy.jpg', 'ada.jpg', >>> 'carl.jpg', 'lena.png', 'easy2.png'] >>> img_fpath_list = [ut.grab_test_imgpath(key) for key in key_list] >>> arg_list1 = [(ut.augpath(img_fpath, '_testgen'), img_fpath, (0, 0, 100, 100), 0.0, (545, 372), []) for img_fpath in img_fpath_list[0:1]] >>> arg_list2 = [(ut.augpath(img_fpath, '_testgen'), img_fpath, (0, 0, 100, 100), 0.0, (545, 372), []) for img_fpath in img_fpath_list] >>> #arg_list3 = [(count, fpath, {}) for count, fpath in enumerate(ut.get_list_column(arg_list1, 0))] >>> #arg_list4 = [(count, fpath, {}) for count, fpath in enumerate(ut.get_list_column(arg_list2, 0))] >>> ut.remove_file_list(ut.get_list_column(arg_list2, 0)) >>> chips1 = [x for x in ut.generate2(gen_chip, arg_list1)] >>> chips2 = [y for y in ut.generate2(gen_chip, arg_list2, force_serial=True)] >>> #feats3 = [z for z in ut.generate2(gen_feat_worker, arg_list3)] >>> #feats4 = [w for w in ut.generate2(gen_feat_worker, arg_list4)] Example3: >>> # DISABLE_DOCTEST >>> # FAILING_DOCTEST >>> # Trying to recreate the freeze seen in IBEIS >>> # Extremely weird case: freezes only if dsize > (313, 313) AND __testwarp was called beforehand. >>> # otherwise the parallel loop works fine. Could be an opencv 3.0.0-dev issue. >>> import vtool as vt >>> import utool as ut >>> from ibeis.algo.preproc.preproc_chip import gen_chip >>> import cv2 >>> from utool.util_parallel import __testwarp >>> key_list = ['grace.jpg', 'easy1.png', 'ada2.jpg', 'easy3.png', >>> 'hard3.png', 'zebra.png', 'patsy.jpg', 'ada.jpg', >>> 'carl.jpg', 'lena.png', 'easy2.png'] >>> img_fpath_list = [ut.grab_test_imgpath(key) for key in key_list] >>> arg_list1 = [(vt.imread(fpath),) for fpath in img_fpath_list[0:1]] >>> arg_list2 = [(vt.imread(fpath),) for fpath in img_fpath_list] >>> #new1 = [x for x in ut.generate2(__testwarp, arg_list1)] >>> new1 = __testwarp(arg_list1[0]) >>> new2 = [y for y in ut.generate2(__testwarp, arg_list2, force_serial=False)] >>> #print('new2 = %r' % (new2,)) #Example4: # >>> # Freakin weird. When IBEIS Runs generate it doesn't close the processes # >>> # UNSTABLE_DOCTEST # >>> # python -m utool.util_parallel --test-generate:4 # >>> # Trying to see if we can recreate the problem where there are # >>> # defunct python processes # >>> import utool as ut # >>> #num = 8700 # parallel is slower for smaller numbers # >>> num = 70000 # parallel has an initial (~.1 second startup overhead) # >>> print('TESTING PARALLEL') # >>> flag_generator1 = list(ut.generate2(ut.is_prime, range(0, num))) # >>> flag_generator1 = list(ut.generate2(ut.is_prime, range(0, num))) # >>> import time # >>> time.sleep(10) """ if verbose is None: verbose = 2 if ntasks is None: ntasks = nTasks if ntasks is None: try: ntasks = len(args_gen) except TypeError: # Cast to a list args_gen = list(args_gen) ntasks = len(args_gen) if ntasks == 1 or ntasks < __MIN_PARALLEL_TASKS__: force_serial = True if __FORCE_SERIAL__: force_serial = __FORCE_SERIAL__ if ntasks == 0: if verbose: print('[ut.generate2] submitted 0 tasks') raise StopIteration if nprocs is None: nprocs = min(ntasks, get_default_numprocs()) if nprocs == 1: force_serial = True if kw_gen is None: kw_gen = [{}] * ntasks if isinstance(kw_gen, dict): # kw_gen can be a single dict applied to everything kw_gen = [kw_gen] * ntasks if force_serial: for result in _generate_serial2(func, args_gen, kw_gen, ntasks=ntasks, progkw=progkw, verbose=verbose): yield result else: if verbose: gentype = 'mp' if use_pool else 'futures' fmtstr = '[generate2] executing {} {} tasks using {} {} procs' print(fmtstr.format(ntasks, get_funcname(func), nprocs, gentype)) if verbose > 1: lbl = '(pargen) %s: ' % (get_funcname(func),) progkw_ = dict(freq=None, bs=True, adjust=False, freq_est='absolute') progkw_.update(progkw) # print('progkw_.update = {!r}'.format(progkw_.update)) progpart = util_progress.ProgPartial(length=ntasks, lbl=lbl, **progkw_) if use_pool: # Use multiprocessing if chunksize is None: chunksize = max(min(4, ntasks), min(8, ntasks // (nprocs ** 2))) try: pool = multiprocessing.Pool(nprocs) if ordered: pmap_func = pool.imap else: pmap_func = pool.imap_unordered wrapped_arg_gen = zip([func] * len(args_gen), args_gen, kw_gen) res_gen = pmap_func(_kw_wrap_worker, wrapped_arg_gen, chunksize) if verbose > 1: res_gen = progpart(res_gen) for res in res_gen: yield res finally: pool.close() pool.join() else: # Use futures executor = futures.ProcessPoolExecutor(nprocs) try: fs_list = [executor.submit(func, *a, **k) for a, k in zip(args_gen, kw_gen)] fs_gen = fs_list if not ordered: fs_gen = futures.as_completed(fs_gen) if verbose > 1: fs_gen = progpart(fs_gen) for fs in fs_gen: yield fs.result() finally: executor.shutdown(wait=True)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 11; 2, function_name:buffered_generator; 3, parameters; 3, 4; 3, 5; 3, 8; 4, identifier:source_gen; 5, default_parameter; 5, 6; 5, 7; 6, identifier:buffer_size; 7, integer:2; 8, default_parameter; 8, 9; 8, 10; 9, identifier:use_multiprocessing; 10, False; 11, block; 11, 12; 11, 14; 11, 24; 11, 95; 11, 96; 11, 97; 11, 98; 11, 109; 11, 110; 11, 111; 11, 112; 11, 116; 11, 134; 11, 135; 11, 141; 11, 147; 12, expression_statement; 12, 13; 13, comment; 14, if_statement; 14, 15; 14, 18; 15, comparison_operator:<; 15, 16; 15, 17; 16, identifier:buffer_size; 17, integer:2; 18, block; 18, 19; 19, raise_statement; 19, 20; 20, call; 20, 21; 20, 22; 21, identifier:RuntimeError; 22, argument_list; 22, 23; 23, string:"Minimal buffer_ size is 2!"; 24, if_statement; 24, 25; 24, 26; 24, 79; 25, identifier:use_multiprocessing; 26, block; 26, 27; 26, 32; 26, 33; 26, 69; 26, 75; 27, expression_statement; 27, 28; 28, call; 28, 29; 28, 30; 29, identifier:print; 30, argument_list; 30, 31; 31, string:'WARNING seems to freeze if passed in a generator'; 32, comment; 33, if_statement; 33, 34; 33, 35; 33, 61; 34, False; 35, block; 35, 36; 35, 55; 36, expression_statement; 36, 37; 37, assignment; 37, 38; 37, 39; 38, identifier:pool; 39, call; 39, 40; 39, 43; 40, attribute; 40, 41; 40, 42; 41, identifier:multiprocessing; 42, identifier:Pool; 43, argument_list; 43, 44; 43, 49; 43, 52; 44, keyword_argument; 44, 45; 44, 46; 45, identifier:processes; 46, call; 46, 47; 46, 48; 47, identifier:get_default_numprocs; 48, argument_list; 49, keyword_argument; 49, 50; 49, 51; 50, identifier:initializer; 51, identifier:init_worker; 52, keyword_argument; 52, 53; 52, 54; 53, identifier:maxtasksperchild; 54, None; 55, expression_statement; 55, 56; 56, assignment; 56, 57; 56, 58; 57, identifier:Process; 58, attribute; 58, 59; 58, 60; 59, identifier:pool; 60, identifier:Process; 61, else_clause; 61, 62; 62, block; 62, 63; 63, expression_statement; 63, 64; 64, assignment; 64, 65; 64, 66; 65, identifier:Process; 66, attribute; 66, 67; 66, 68; 67, identifier:multiprocessing; 68, identifier:Process; 69, expression_statement; 69, 70; 70, assignment; 70, 71; 70, 72; 71, identifier:_Queue; 72, attribute; 72, 73; 72, 74; 73, identifier:multiprocessing; 74, identifier:Queue; 75, expression_statement; 75, 76; 76, assignment; 76, 77; 76, 78; 77, identifier:target; 78, identifier:_buffered_generation_process; 79, else_clause; 79, 80; 80, block; 80, 81; 80, 87; 80, 91; 81, expression_statement; 81, 82; 82, assignment; 82, 83; 82, 84; 83, identifier:_Queue; 84, attribute; 84, 85; 84, 86; 85, identifier:queue; 86, identifier:Queue; 87, expression_statement; 87, 88; 88, assignment; 88, 89; 88, 90; 89, identifier:Process; 90, identifier:KillableThread; 91, expression_statement; 91, 92; 92, assignment; 92, 93; 92, 94; 93, identifier:target; 94, identifier:_buffered_generation_thread; 95, comment; 96, comment; 97, comment; 98, expression_statement; 98, 99; 99, assignment; 99, 100; 99, 101; 100, identifier:buffer_; 101, call; 101, 102; 101, 103; 102, identifier:_Queue; 103, argument_list; 103, 104; 104, keyword_argument; 104, 105; 104, 106; 105, identifier:maxsize; 106, binary_operator:-; 106, 107; 106, 108; 107, identifier:buffer_size; 108, integer:1; 109, comment; 110, comment; 111, comment; 112, expression_statement; 112, 113; 113, assignment; 113, 114; 113, 115; 114, identifier:sentinal; 115, identifier:StopIteration; 116, expression_statement; 116, 117; 117, assignment; 117, 118; 117, 119; 118, identifier:process; 119, call; 119, 120; 119, 121; 120, identifier:Process; 121, argument_list; 121, 122; 121, 125; 122, keyword_argument; 122, 123; 122, 124; 123, identifier:target; 124, identifier:target; 125, keyword_argument; 125, 126; 125, 127; 126, identifier:args; 127, tuple; 127, 128; 127, 132; 127, 133; 128, call; 128, 129; 128, 130; 129, identifier:iter; 130, argument_list; 130, 131; 131, identifier:source_gen; 132, identifier:buffer_; 133, identifier:sentinal; 134, comment; 135, expression_statement; 135, 136; 136, assignment; 136, 137; 136, 140; 137, attribute; 137, 138; 137, 139; 138, identifier:process; 139, identifier:daemon; 140, True; 141, expression_statement; 141, 142; 142, call; 142, 143; 142, 146; 143, attribute; 143, 144; 143, 145; 144, identifier:process; 145, identifier:start; 146, argument_list; 147, while_statement; 147, 148; 147, 149; 147, 150; 148, True; 149, comment; 150, block; 150, 151; 150, 159; 150, 166; 151, expression_statement; 151, 152; 152, assignment; 152, 153; 152, 154; 153, identifier:output; 154, call; 154, 155; 154, 158; 155, attribute; 155, 156; 155, 157; 156, identifier:buffer_; 157, identifier:get; 158, argument_list; 159, if_statement; 159, 160; 159, 163; 160, comparison_operator:is; 160, 161; 160, 162; 161, identifier:output; 162, identifier:sentinal; 163, block; 163, 164; 164, raise_statement; 164, 165; 165, identifier:StopIteration; 166, expression_statement; 166, 167; 167, yield; 167, 168; 168, identifier:output
def buffered_generator(source_gen, buffer_size=2, use_multiprocessing=False): r""" Generator that runs a slow source generator in a separate process. My generate function still seems faster on test cases. However, this function is more flexible in its compatability. Args: source_gen (iterable): slow generator buffer_size (int): the maximal number of items to pre-generate (length of the buffer) (default = 2) use_multiprocessing (bool): if False uses GIL-hindered threading instead of multiprocessing (defualt = False). Note: use_multiprocessing = True seems to freeze if passed in a generator built by six.moves.map. References: Taken from Sander Dieleman's data augmentation pipeline https://github.com/benanne/kaggle-ndsb/blob/11a66cdbddee16c69514b9530a727df0ac6e136f/buffering.py CommandLine: python -m utool.util_parallel --test-buffered_generator:0 python -m utool.util_parallel --test-buffered_generator:1 Ignore: >>> #functime = timeit.timeit( >>> # 'ut.is_prime(' + str(prime) + ')', setup='import utool as ut', >>> # number=500) / 1000.0 Example: >>> # DISABLE_DOCTEST >>> # UNSTABLE_DOCTEST >>> from utool.util_parallel import * # NOQA >>> import utool as ut >>> num = 2 ** 14 >>> func = ut.is_prime >>> data = [38873] * num >>> data = list(range(num)) >>> with ut.Timer('serial') as t1: ... result1 = list(map(func, data)) >>> with ut.Timer('ut.generate2') as t3: ... result3 = list(ut.generate2(func, zip(data), chunksize=2, quiet=1, verbose=0)) >>> with ut.Timer('ut.buffered_generator') as t2: ... result2 = list(ut.buffered_generator(map(func, data))) >>> assert len(result1) == num and len(result2) == num and len(result3) == num >>> assert result3 == result2, 'inconsistent results' >>> assert result1 == result2, 'inconsistent results' Example1: >>> # DISABLE_DOCTEST >>> # VERYSLLOOWWW_DOCTEST >>> from utool.util_parallel import _test_buffered_generator >>> _test_buffered_generator2() """ if buffer_size < 2: raise RuntimeError("Minimal buffer_ size is 2!") if use_multiprocessing: print('WARNING seems to freeze if passed in a generator') #assert False, 'dont use this buffered multiprocessing' if False: pool = multiprocessing.Pool(processes=get_default_numprocs(), initializer=init_worker, maxtasksperchild=None) Process = pool.Process else: Process = multiprocessing.Process _Queue = multiprocessing.Queue target = _buffered_generation_process else: _Queue = queue.Queue Process = KillableThread target = _buffered_generation_thread # the effective buffer_ size is one less, because the generation process # will generate one extra element and block until there is room in the # buffer_. buffer_ = _Queue(maxsize=buffer_size - 1) # previously None was used as a sentinal, which fails when source_gen # genrates None need to make object that it will not be generated by the # process. A reasonable hack is to use the StopIteration exception instead sentinal = StopIteration process = Process( target=target, args=(iter(source_gen), buffer_, sentinal) ) #if not use_multiprocessing: process.daemon = True process.start() while True: #output = buffer_.get(timeout=1.0) output = buffer_.get() if output is sentinal: raise StopIteration yield output
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 8; 2, function_name:sort_window_ids; 3, parameters; 3, 4; 3, 5; 4, identifier:winid_list; 5, default_parameter; 5, 6; 5, 7; 6, identifier:order; 7, string:'mru'; 8, block; 8, 9; 8, 11; 8, 16; 8, 25; 8, 35; 9, expression_statement; 9, 10; 10, comment; 11, import_statement; 11, 12; 12, aliased_import; 12, 13; 12, 15; 13, dotted_name; 13, 14; 14, identifier:utool; 15, identifier:ut; 16, expression_statement; 16, 17; 17, assignment; 17, 18; 17, 19; 18, identifier:winid_order; 19, call; 19, 20; 19, 23; 20, attribute; 20, 21; 20, 22; 21, identifier:XCtrl; 22, identifier:sorted_window_ids; 23, argument_list; 23, 24; 24, identifier:order; 25, expression_statement; 25, 26; 26, assignment; 26, 27; 26, 28; 27, identifier:sorted_win_ids; 28, call; 28, 29; 28, 32; 29, attribute; 29, 30; 29, 31; 30, identifier:ut; 31, identifier:isect; 32, argument_list; 32, 33; 32, 34; 33, identifier:winid_order; 34, identifier:winid_list; 35, return_statement; 35, 36; 36, identifier:sorted_win_ids
def sort_window_ids(winid_list, order='mru'): """ Orders window ids by most recently used """ import utool as ut winid_order = XCtrl.sorted_window_ids(order) sorted_win_ids = ut.isect(winid_order, winid_list) return sorted_win_ids
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:__infer_setup_kwargs; 3, parameters; 3, 4; 3, 5; 4, identifier:module; 5, identifier:kwargs; 6, block; 6, 7; 6, 9; 6, 10; 6, 11; 6, 12; 6, 13; 6, 14; 6, 20; 6, 21; 6, 22; 6, 23; 6, 24; 6, 25; 6, 26; 6, 36; 6, 54; 6, 72; 6, 73; 6, 74; 6, 75; 6, 76; 6, 77; 6, 78; 6, 79; 6, 99; 6, 100; 7, expression_statement; 7, 8; 8, comment; 9, comment; 10, comment; 11, comment; 12, comment; 13, comment; 14, expression_statement; 14, 15; 15, assignment; 15, 16; 15, 17; 16, identifier:name; 17, subscript; 17, 18; 17, 19; 18, identifier:kwargs; 19, string:'name'; 20, comment; 21, comment; 22, comment; 23, comment; 24, comment; 25, comment; 26, expression_statement; 26, 27; 27, assignment; 27, 28; 27, 29; 28, identifier:packages; 29, call; 29, 30; 29, 33; 30, attribute; 30, 31; 30, 32; 31, identifier:kwargs; 32, identifier:get; 33, argument_list; 33, 34; 33, 35; 34, string:'packages'; 35, list:[]; 36, if_statement; 36, 37; 36, 40; 37, comparison_operator:not; 37, 38; 37, 39; 38, identifier:name; 39, identifier:packages; 40, block; 40, 41; 40, 48; 41, expression_statement; 41, 42; 42, call; 42, 43; 42, 46; 43, attribute; 43, 44; 43, 45; 44, identifier:packages; 45, identifier:append; 46, argument_list; 46, 47; 47, identifier:name; 48, expression_statement; 48, 49; 49, assignment; 49, 50; 49, 53; 50, subscript; 50, 51; 50, 52; 51, identifier:kwargs; 52, string:'packages'; 53, identifier:packages; 54, if_statement; 54, 55; 54, 58; 55, comparison_operator:not; 55, 56; 55, 57; 56, string:'version'; 57, identifier:kwargs; 58, block; 58, 59; 58, 66; 59, expression_statement; 59, 60; 60, assignment; 60, 61; 60, 62; 61, identifier:version; 62, call; 62, 63; 62, 64; 63, identifier:parse_package_for_version; 64, argument_list; 64, 65; 65, identifier:name; 66, expression_statement; 66, 67; 67, assignment; 67, 68; 67, 71; 68, subscript; 68, 69; 68, 70; 69, identifier:kwargs; 70, string:'version'; 71, identifier:version; 72, comment; 73, comment; 74, comment; 75, comment; 76, comment; 77, comment; 78, comment; 79, if_statement; 79, 80; 79, 83; 80, comparison_operator:not; 80, 81; 80, 82; 81, string:'license'; 82, identifier:kwargs; 83, block; 83, 84; 84, try_statement; 84, 85; 84, 95; 85, block; 85, 86; 86, expression_statement; 86, 87; 87, assignment; 87, 88; 87, 91; 88, subscript; 88, 89; 88, 90; 89, identifier:kwargs; 90, string:'license'; 91, call; 91, 92; 91, 93; 92, identifier:read_license; 93, argument_list; 93, 94; 94, string:'LICENSE'; 95, except_clause; 95, 96; 95, 97; 96, identifier:IOError; 97, block; 97, 98; 98, pass_statement; 99, comment; 100, if_statement; 100, 101; 100, 104; 101, comparison_operator:not; 101, 102; 101, 103; 102, string:'long_description'; 103, identifier:kwargs; 104, block; 104, 105; 105, expression_statement; 105, 106; 106, assignment; 106, 107; 106, 110; 107, subscript; 107, 108; 107, 109; 108, identifier:kwargs; 109, string:'long_description'; 110, call; 110, 111; 110, 112; 111, identifier:parse_readme; 112, argument_list
def __infer_setup_kwargs(module, kwargs): """ Implicitly build kwargs based on standard info """ # Get project name from the module #if 'name' not in kwargs: # kwargs['name'] = module.__name__ #else: # raise AssertionError('must specify module name!') name = kwargs['name'] # Our projects depend on utool #if kwargs['name'] != 'utool': # install_requires = kwargs.get('install_requires', []) # if 'utool' not in install_requires: # install_requires.append('utool') # kwargs['install_requires'] = install_requires packages = kwargs.get('packages', []) if name not in packages: packages.append(name) kwargs['packages'] = packages if 'version' not in kwargs: version = parse_package_for_version(name) kwargs['version'] = version # Parse version #if 'version' not in kwargs: # if module is None: # version_errmsg = 'You must include a version (preferably one that matches the __version__ variable in your modules init file' # raise AssertionError(version_errmsg) # else: # Parse license if 'license' not in kwargs: try: kwargs['license'] = read_license('LICENSE') except IOError: pass # Parse readme if 'long_description' not in kwargs: kwargs['long_description'] = parse_readme()
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 13; 2, function_name:on_exception_report_input; 3, parameters; 3, 4; 3, 7; 3, 10; 4, default_parameter; 4, 5; 4, 6; 5, identifier:func_; 6, None; 7, default_parameter; 7, 8; 7, 9; 8, identifier:force; 9, False; 10, default_parameter; 10, 11; 10, 12; 11, identifier:keys; 12, None; 13, block; 13, 14; 13, 16; 13, 384; 14, expression_statement; 14, 15; 15, comment; 16, function_definition; 16, 17; 16, 18; 16, 20; 17, function_name:_closure_onexceptreport; 18, parameters; 18, 19; 19, identifier:func; 20, block; 20, 21; 20, 30; 20, 374; 20, 382; 21, if_statement; 21, 22; 21, 27; 22, boolean_operator:and; 22, 23; 22, 25; 23, not_operator; 23, 24; 24, identifier:ONEX_REPORT_INPUT; 25, not_operator; 25, 26; 26, identifier:force; 27, block; 27, 28; 28, return_statement; 28, 29; 29, identifier:func; 30, decorated_definition; 30, 31; 30, 38; 30, 39; 31, decorator; 31, 32; 32, call; 32, 33; 32, 34; 33, identifier:ignores_exc_tb; 34, argument_list; 34, 35; 35, keyword_argument; 35, 36; 35, 37; 36, identifier:outer_wrapper; 37, False; 38, comment; 39, function_definition; 39, 40; 39, 41; 39, 46; 40, function_name:wrp_onexceptreport; 41, parameters; 41, 42; 41, 44; 42, list_splat_pattern; 42, 43; 43, identifier:args; 44, dictionary_splat_pattern; 44, 45; 45, identifier:kwargs; 46, block; 46, 47; 47, try_statement; 47, 48; 47, 49; 47, 50; 47, 51; 47, 52; 47, 61; 48, comment; 49, comment; 50, comment; 51, comment; 52, block; 52, 53; 53, return_statement; 53, 54; 54, call; 54, 55; 54, 56; 55, identifier:func; 56, argument_list; 56, 57; 56, 59; 57, list_splat; 57, 58; 58, identifier:args; 59, dictionary_splat; 59, 60; 60, identifier:kwargs; 61, except_clause; 61, 62; 61, 66; 62, as_pattern; 62, 63; 62, 64; 63, identifier:Exception; 64, as_pattern_target; 64, 65; 65, identifier:ex; 66, block; 66, 67; 66, 72; 66, 77; 66, 276; 66, 300; 66, 329; 66, 344; 66, 353; 66, 362; 66, 373; 67, import_from_statement; 67, 68; 67, 70; 68, dotted_name; 68, 69; 69, identifier:utool; 70, dotted_name; 70, 71; 71, identifier:util_str; 72, expression_statement; 72, 73; 73, call; 73, 74; 73, 75; 74, identifier:print; 75, argument_list; 75, 76; 76, string:'ERROR occured! Reporting input to function'; 77, if_statement; 77, 78; 77, 81; 78, comparison_operator:is; 78, 79; 78, 80; 79, identifier:keys; 80, None; 81, block; 81, 82; 81, 87; 81, 92; 81, 97; 81, 106; 81, 116; 81, 126; 81, 139; 81, 148; 81, 158; 81, 173; 81, 189; 81, 206; 81, 224; 81, 234; 81, 256; 81, 274; 81, 275; 82, import_from_statement; 82, 83; 82, 85; 83, dotted_name; 83, 84; 84, identifier:utool; 85, dotted_name; 85, 86; 86, identifier:util_inspect; 87, import_from_statement; 87, 88; 87, 90; 88, dotted_name; 88, 89; 89, identifier:utool; 90, dotted_name; 90, 91; 91, identifier:util_list; 92, import_from_statement; 92, 93; 92, 95; 93, dotted_name; 93, 94; 94, identifier:utool; 95, dotted_name; 95, 96; 96, identifier:util_dict; 97, expression_statement; 97, 98; 98, assignment; 98, 99; 98, 100; 99, identifier:argspec; 100, call; 100, 101; 100, 104; 101, attribute; 101, 102; 101, 103; 102, identifier:util_inspect; 103, identifier:get_func_argspec; 104, argument_list; 104, 105; 105, identifier:func; 106, expression_statement; 106, 107; 107, assignment; 107, 108; 107, 109; 108, identifier:in_kwargs_flags; 109, list_comprehension; 109, 110; 109, 113; 110, comparison_operator:in; 110, 111; 110, 112; 111, identifier:key; 112, identifier:kwargs; 113, for_in_clause; 113, 114; 113, 115; 114, identifier:key; 115, identifier:keys; 116, expression_statement; 116, 117; 117, assignment; 117, 118; 117, 119; 118, identifier:kwarg_keys; 119, call; 119, 120; 119, 123; 120, attribute; 120, 121; 120, 122; 121, identifier:util_list; 122, identifier:compress; 123, argument_list; 123, 124; 123, 125; 124, identifier:keys; 125, identifier:in_kwargs_flags; 126, expression_statement; 126, 127; 127, assignment; 127, 128; 127, 129; 128, identifier:kwarg_vals; 129, list_comprehension; 129, 130; 129, 136; 130, call; 130, 131; 130, 134; 131, attribute; 131, 132; 131, 133; 132, identifier:kwargs; 133, identifier:get; 134, argument_list; 134, 135; 135, identifier:key; 136, for_in_clause; 136, 137; 136, 138; 137, identifier:key; 138, identifier:kwarg_keys; 139, expression_statement; 139, 140; 140, assignment; 140, 141; 140, 142; 141, identifier:flags; 142, call; 142, 143; 142, 146; 143, attribute; 143, 144; 143, 145; 144, identifier:util_list; 145, identifier:not_list; 146, argument_list; 146, 147; 147, identifier:in_kwargs_flags; 148, expression_statement; 148, 149; 149, assignment; 149, 150; 149, 151; 150, identifier:arg_keys; 151, call; 151, 152; 151, 155; 152, attribute; 152, 153; 152, 154; 153, identifier:util_list; 154, identifier:compress; 155, argument_list; 155, 156; 155, 157; 156, identifier:keys; 157, identifier:flags; 158, expression_statement; 158, 159; 159, assignment; 159, 160; 159, 161; 160, identifier:arg_idxs; 161, list_comprehension; 161, 162; 161, 170; 162, call; 162, 163; 162, 168; 163, attribute; 163, 164; 163, 167; 164, attribute; 164, 165; 164, 166; 165, identifier:argspec; 166, identifier:args; 167, identifier:index; 168, argument_list; 168, 169; 169, identifier:key; 170, for_in_clause; 170, 171; 170, 172; 171, identifier:key; 172, identifier:arg_keys; 173, expression_statement; 173, 174; 174, assignment; 174, 175; 174, 176; 175, identifier:num_nodefault; 176, binary_operator:-; 176, 177; 176, 183; 177, call; 177, 178; 177, 179; 178, identifier:len; 179, argument_list; 179, 180; 180, attribute; 180, 181; 180, 182; 181, identifier:argspec; 182, identifier:args; 183, call; 183, 184; 183, 185; 184, identifier:len; 185, argument_list; 185, 186; 186, attribute; 186, 187; 186, 188; 187, identifier:argspec; 188, identifier:defaults; 189, expression_statement; 189, 190; 190, assignment; 190, 191; 190, 192; 191, identifier:default_vals; 192, parenthesized_expression; 192, 193; 193, binary_operator:+; 193, 194; 193, 200; 194, parenthesized_expression; 194, 195; 195, binary_operator:*; 195, 196; 195, 198; 196, list:[None]; 196, 197; 197, None; 198, parenthesized_expression; 198, 199; 199, identifier:num_nodefault; 200, call; 200, 201; 200, 202; 201, identifier:list; 202, argument_list; 202, 203; 203, attribute; 203, 204; 203, 205; 204, identifier:argspec; 205, identifier:defaults; 206, expression_statement; 206, 207; 207, assignment; 207, 208; 207, 209; 208, identifier:args_; 209, binary_operator:+; 209, 210; 209, 214; 210, call; 210, 211; 210, 212; 211, identifier:list; 212, argument_list; 212, 213; 213, identifier:args; 214, subscript; 214, 215; 214, 216; 215, identifier:default_vals; 216, slice; 216, 217; 216, 223; 217, binary_operator:+; 217, 218; 217, 222; 218, call; 218, 219; 218, 220; 219, identifier:len; 220, argument_list; 220, 221; 221, identifier:args; 222, integer:1; 223, colon; 224, expression_statement; 224, 225; 225, assignment; 225, 226; 225, 227; 226, identifier:arg_vals; 227, call; 227, 228; 227, 231; 228, attribute; 228, 229; 228, 230; 229, identifier:util_list; 230, identifier:take; 231, argument_list; 231, 232; 231, 233; 232, identifier:args_; 233, identifier:arg_idxs; 234, expression_statement; 234, 235; 235, assignment; 235, 236; 235, 237; 236, identifier:requested_dict; 237, call; 237, 238; 237, 239; 238, identifier:dict; 239, argument_list; 239, 240; 240, call; 240, 241; 240, 244; 241, attribute; 241, 242; 241, 243; 242, identifier:util_list; 243, identifier:flatten; 244, argument_list; 244, 245; 245, list:[zip(kwarg_keys, kwarg_vals), zip(arg_keys, arg_vals)]; 245, 246; 245, 251; 246, call; 246, 247; 246, 248; 247, identifier:zip; 248, argument_list; 248, 249; 248, 250; 249, identifier:kwarg_keys; 250, identifier:kwarg_vals; 251, call; 251, 252; 251, 253; 252, identifier:zip; 253, argument_list; 253, 254; 253, 255; 254, identifier:arg_keys; 255, identifier:arg_vals; 256, expression_statement; 256, 257; 257, call; 257, 258; 257, 259; 258, identifier:print; 259, argument_list; 259, 260; 260, binary_operator:+; 260, 261; 260, 262; 261, string:'input dict = '; 262, call; 262, 263; 262, 266; 263, attribute; 263, 264; 263, 265; 264, identifier:util_str; 265, identifier:repr4; 266, argument_list; 266, 267; 267, call; 267, 268; 267, 271; 268, attribute; 268, 269; 268, 270; 269, identifier:util_dict; 270, identifier:dict_subset; 271, argument_list; 271, 272; 271, 273; 272, identifier:requested_dict; 273, identifier:keys; 274, comment; 275, pass_statement; 276, expression_statement; 276, 277; 277, assignment; 277, 278; 277, 279; 278, identifier:arg_strs; 279, call; 279, 280; 279, 283; 280, attribute; 280, 281; 280, 282; 281, string:', '; 282, identifier:join; 283, argument_list; 283, 284; 284, list_comprehension; 284, 285; 284, 297; 285, call; 285, 286; 285, 287; 286, identifier:repr; 287, argument_list; 287, 288; 288, call; 288, 289; 288, 292; 289, attribute; 289, 290; 289, 291; 290, identifier:util_str; 291, identifier:truncate_str; 292, argument_list; 292, 293; 293, call; 293, 294; 293, 295; 294, identifier:str; 295, argument_list; 295, 296; 296, identifier:arg; 297, for_in_clause; 297, 298; 297, 299; 298, identifier:arg; 299, identifier:args; 300, expression_statement; 300, 301; 301, assignment; 301, 302; 301, 303; 302, identifier:kwarg_strs; 303, call; 303, 304; 303, 307; 304, attribute; 304, 305; 304, 306; 305, string:', '; 306, identifier:join; 307, argument_list; 307, 308; 308, list_comprehension; 308, 309; 308, 319; 309, call; 309, 310; 309, 313; 310, attribute; 310, 311; 310, 312; 311, identifier:util_str; 312, identifier:truncate_str; 313, argument_list; 313, 314; 314, binary_operator:%; 314, 315; 314, 316; 315, string:'%s=%r'; 316, tuple; 316, 317; 316, 318; 317, identifier:key; 318, identifier:val; 319, for_in_clause; 319, 320; 319, 323; 320, pattern_list; 320, 321; 320, 322; 321, identifier:key; 322, identifier:val; 323, call; 323, 324; 323, 327; 324, attribute; 324, 325; 324, 326; 325, identifier:six; 326, identifier:iteritems; 327, argument_list; 327, 328; 328, identifier:kwargs; 329, expression_statement; 329, 330; 330, assignment; 330, 331; 330, 332; 331, identifier:msg; 332, parenthesized_expression; 332, 333; 333, binary_operator:%; 333, 334; 333, 335; 334, string:'\nERROR: funcname=%r,\n * args=%s,\n * kwargs=%r\n'; 335, tuple; 335, 336; 335, 342; 335, 343; 336, call; 336, 337; 336, 340; 337, attribute; 337, 338; 337, 339; 338, identifier:meta_util_six; 339, identifier:get_funcname; 340, argument_list; 340, 341; 341, identifier:func; 342, identifier:arg_strs; 343, identifier:kwarg_strs; 344, expression_statement; 344, 345; 345, augmented_assignment:+=; 345, 346; 345, 347; 346, identifier:msg; 347, binary_operator:%; 347, 348; 347, 349; 348, string:' * len(args) = %r\n'; 349, call; 349, 350; 349, 351; 350, identifier:len; 351, argument_list; 351, 352; 352, identifier:args; 353, expression_statement; 353, 354; 354, augmented_assignment:+=; 354, 355; 354, 356; 355, identifier:msg; 356, binary_operator:%; 356, 357; 356, 358; 357, string:' * len(kwargs) = %r\n'; 358, call; 358, 359; 358, 360; 359, identifier:len; 360, argument_list; 360, 361; 361, identifier:kwargs; 362, expression_statement; 362, 363; 363, call; 363, 364; 363, 367; 364, attribute; 364, 365; 364, 366; 365, identifier:util_dbg; 366, identifier:printex; 367, argument_list; 367, 368; 367, 369; 367, 370; 368, identifier:ex; 369, identifier:msg; 370, keyword_argument; 370, 371; 370, 372; 371, identifier:pad_stdout; 372, True; 373, raise_statement; 374, expression_statement; 374, 375; 375, assignment; 375, 376; 375, 377; 376, identifier:wrp_onexceptreport; 377, call; 377, 378; 377, 379; 378, identifier:preserve_sig; 379, argument_list; 379, 380; 379, 381; 380, identifier:wrp_onexceptreport; 381, identifier:func; 382, return_statement; 382, 383; 383, identifier:wrp_onexceptreport; 384, if_statement; 384, 385; 384, 388; 384, 391; 385, comparison_operator:is; 385, 386; 385, 387; 386, identifier:func_; 387, None; 388, block; 388, 389; 389, return_statement; 389, 390; 390, identifier:_closure_onexceptreport; 391, else_clause; 391, 392; 392, block; 392, 393; 393, return_statement; 393, 394; 394, call; 394, 395; 394, 396; 395, identifier:_closure_onexceptreport; 396, argument_list; 396, 397; 397, identifier:func_
def on_exception_report_input(func_=None, force=False, keys=None): """ If an error is thrown in the scope of this function's stack frame then the decorated function name and the arguments passed to it will be printed to the utool print function. """ def _closure_onexceptreport(func): if not ONEX_REPORT_INPUT and not force: return func @ignores_exc_tb(outer_wrapper=False) #@wraps(func) def wrp_onexceptreport(*args, **kwargs): try: #import utool #if utool.DEBUG: # print('[IN EXCPRPT] args=%r' % (args,)) # print('[IN EXCPRPT] kwargs=%r' % (kwargs,)) return func(*args, **kwargs) except Exception as ex: from utool import util_str print('ERROR occured! Reporting input to function') if keys is not None: from utool import util_inspect from utool import util_list from utool import util_dict argspec = util_inspect.get_func_argspec(func) in_kwargs_flags = [key in kwargs for key in keys] kwarg_keys = util_list.compress(keys, in_kwargs_flags) kwarg_vals = [kwargs.get(key) for key in kwarg_keys] flags = util_list.not_list(in_kwargs_flags) arg_keys = util_list.compress(keys, flags) arg_idxs = [argspec.args.index(key) for key in arg_keys] num_nodefault = len(argspec.args) - len(argspec.defaults) default_vals = (([None] * (num_nodefault)) + list(argspec.defaults)) args_ = list(args) + default_vals[len(args) + 1:] arg_vals = util_list.take(args_, arg_idxs) requested_dict = dict(util_list.flatten( [zip(kwarg_keys, kwarg_vals), zip(arg_keys, arg_vals)])) print('input dict = ' + util_str.repr4( util_dict.dict_subset(requested_dict, keys))) # (print out specific keys only) pass arg_strs = ', '.join([repr(util_str.truncate_str(str(arg))) for arg in args]) kwarg_strs = ', '.join([ util_str.truncate_str('%s=%r' % (key, val)) for key, val in six.iteritems(kwargs)]) msg = ('\nERROR: funcname=%r,\n * args=%s,\n * kwargs=%r\n' % ( meta_util_six.get_funcname(func), arg_strs, kwarg_strs)) msg += ' * len(args) = %r\n' % len(args) msg += ' * len(kwargs) = %r\n' % len(kwargs) util_dbg.printex(ex, msg, pad_stdout=True) raise wrp_onexceptreport = preserve_sig(wrp_onexceptreport, func) return wrp_onexceptreport if func_ is None: return _closure_onexceptreport else: return _closure_onexceptreport(func_)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:accepts_scalar_input; 3, parameters; 3, 4; 4, identifier:func; 5, block; 5, 6; 5, 8; 5, 9; 5, 76; 5, 84; 6, expression_statement; 6, 7; 7, comment; 8, comment; 9, decorated_definition; 9, 10; 9, 17; 9, 18; 10, decorator; 10, 11; 11, call; 11, 12; 11, 13; 12, identifier:ignores_exc_tb; 13, argument_list; 13, 14; 14, keyword_argument; 14, 15; 14, 16; 15, identifier:outer_wrapper; 16, False; 17, comment; 18, function_definition; 18, 19; 18, 20; 18, 27; 18, 28; 18, 29; 18, 30; 19, function_name:wrp_asi; 20, parameters; 20, 21; 20, 22; 20, 23; 20, 25; 21, identifier:self; 22, identifier:input_; 23, list_splat_pattern; 23, 24; 24, identifier:args; 25, dictionary_splat_pattern; 25, 26; 26, identifier:kwargs; 27, comment; 28, comment; 29, comment; 30, block; 30, 31; 31, if_statement; 31, 32; 31, 38; 31, 39; 31, 50; 32, call; 32, 33; 32, 36; 33, attribute; 33, 34; 33, 35; 34, identifier:util_iter; 35, identifier:isiterable; 36, argument_list; 36, 37; 37, identifier:input_; 38, comment; 39, block; 39, 40; 40, return_statement; 40, 41; 41, call; 41, 42; 41, 43; 42, identifier:func; 43, argument_list; 43, 44; 43, 45; 43, 46; 43, 48; 44, identifier:self; 45, identifier:input_; 46, list_splat; 46, 47; 47, identifier:args; 48, dictionary_splat; 48, 49; 49, identifier:kwargs; 50, else_clause; 50, 51; 50, 52; 50, 53; 51, comment; 52, comment; 53, block; 53, 54; 53, 67; 54, expression_statement; 54, 55; 55, assignment; 55, 56; 55, 57; 56, identifier:ret; 57, call; 57, 58; 57, 59; 58, identifier:func; 59, argument_list; 59, 60; 59, 61; 59, 63; 59, 65; 60, identifier:self; 61, list:[input_]; 61, 62; 62, identifier:input_; 63, list_splat; 63, 64; 64, identifier:args; 65, dictionary_splat; 65, 66; 66, identifier:kwargs; 67, if_statement; 67, 68; 67, 71; 68, comparison_operator:is; 68, 69; 68, 70; 69, identifier:ret; 70, None; 71, block; 71, 72; 72, return_statement; 72, 73; 73, subscript; 73, 74; 73, 75; 74, identifier:ret; 75, integer:0; 76, expression_statement; 76, 77; 77, assignment; 77, 78; 77, 79; 78, identifier:wrp_asi; 79, call; 79, 80; 79, 81; 80, identifier:preserve_sig; 81, argument_list; 81, 82; 81, 83; 82, identifier:wrp_asi; 83, identifier:func; 84, return_statement; 84, 85; 85, identifier:wrp_asi
def accepts_scalar_input(func): """ DEPRICATE in favor of accepts_scalar_input2 only accepts one input as vector accepts_scalar_input is a decorator which expects to be used on class methods. It lets the user pass either a vector or a scalar to a function, as long as the function treats everything like a vector. Input and output is sanitized to the user expected format on return. Args: func (func): Returns: func: wrp_asi CommandLine: python -m utool.util_decor --test-accepts_scalar_input Example: >>> # ENABLE_DOCTEST >>> from utool.util_decor import * # NOQA >>> @accepts_scalar_input ... def foobar(self, list_): ... return [x + 1 for x in list_] >>> self = None # dummy self because this decorator is for classes >>> assert 2 == foobar(self, 1) >>> assert [2, 3] == foobar(self, [1, 2]) """ #@on_exception_report_input @ignores_exc_tb(outer_wrapper=False) #@wraps(func) def wrp_asi(self, input_, *args, **kwargs): #if HAVE_PANDAS: # if isinstance(input_, (pd.DataFrame, pd.Series)): # input_ = input_.values if util_iter.isiterable(input_): # If input is already iterable do default behavior return func(self, input_, *args, **kwargs) else: # If input is scalar, wrap input, execute, and unpack result #ret = func(self, (input_,), *args, **kwargs) ret = func(self, [input_], *args, **kwargs) if ret is not None: return ret[0] wrp_asi = preserve_sig(wrp_asi, func) return wrp_asi
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 9; 2, function_name:preserve_sig; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:wrapper; 5, identifier:orig_func; 6, default_parameter; 6, 7; 6, 8; 7, identifier:force; 8, False; 9, block; 9, 10; 9, 12; 9, 13; 9, 14; 9, 15; 9, 21; 9, 26; 9, 31; 9, 39; 9, 48; 9, 57; 9, 66; 9, 77; 9, 86; 9, 87; 9, 91; 9, 97; 9, 103; 9, 109; 9, 115; 9, 134; 9, 153; 9, 154; 9, 155; 9, 169; 9, 334; 9, 338; 9, 361; 9, 381; 9, 389; 9, 395; 10, expression_statement; 10, 11; 11, comment; 12, comment; 13, comment; 14, comment; 15, import_from_statement; 15, 16; 15, 19; 16, dotted_name; 16, 17; 16, 18; 17, identifier:utool; 18, identifier:_internal; 19, dotted_name; 19, 20; 20, identifier:meta_util_six; 21, import_from_statement; 21, 22; 21, 24; 22, dotted_name; 22, 23; 23, identifier:utool; 24, dotted_name; 24, 25; 25, identifier:util_str; 26, import_from_statement; 26, 27; 26, 29; 27, dotted_name; 27, 28; 28, identifier:utool; 29, dotted_name; 29, 30; 30, identifier:util_inspect; 31, if_statement; 31, 32; 31, 35; 31, 36; 32, comparison_operator:is; 32, 33; 32, 34; 33, identifier:wrapper; 34, identifier:orig_func; 35, comment; 36, block; 36, 37; 37, return_statement; 37, 38; 38, identifier:orig_func; 39, expression_statement; 39, 40; 40, assignment; 40, 41; 40, 42; 41, identifier:orig_docstr; 42, call; 42, 43; 42, 46; 43, attribute; 43, 44; 43, 45; 44, identifier:meta_util_six; 45, identifier:get_funcdoc; 46, argument_list; 46, 47; 47, identifier:orig_func; 48, expression_statement; 48, 49; 49, assignment; 49, 50; 49, 51; 50, identifier:orig_docstr; 51, conditional_expression:if; 51, 52; 51, 53; 51, 56; 52, string:''; 53, comparison_operator:is; 53, 54; 53, 55; 54, identifier:orig_docstr; 55, None; 56, identifier:orig_docstr; 57, expression_statement; 57, 58; 58, assignment; 58, 59; 58, 60; 59, identifier:orig_argspec; 60, call; 60, 61; 60, 64; 61, attribute; 61, 62; 61, 63; 62, identifier:util_inspect; 63, identifier:get_func_argspec; 64, argument_list; 64, 65; 65, identifier:orig_func; 66, expression_statement; 66, 67; 67, assignment; 67, 68; 67, 69; 68, identifier:wrap_name; 69, attribute; 69, 70; 69, 76; 70, call; 70, 71; 70, 74; 71, attribute; 71, 72; 71, 73; 72, identifier:meta_util_six; 73, identifier:get_funccode; 74, argument_list; 74, 75; 75, identifier:wrapper; 76, identifier:co_name; 77, expression_statement; 77, 78; 78, assignment; 78, 79; 78, 80; 79, identifier:orig_name; 80, call; 80, 81; 80, 84; 81, attribute; 81, 82; 81, 83; 82, identifier:meta_util_six; 83, identifier:get_funcname; 84, argument_list; 84, 85; 85, identifier:orig_func; 86, comment; 87, expression_statement; 87, 88; 88, assignment; 88, 89; 88, 90; 89, identifier:_utinfo; 90, dictionary; 91, expression_statement; 91, 92; 92, assignment; 92, 93; 92, 96; 93, subscript; 93, 94; 93, 95; 94, identifier:_utinfo; 95, string:'orig_func'; 96, identifier:orig_func; 97, expression_statement; 97, 98; 98, assignment; 98, 99; 98, 102; 99, subscript; 99, 100; 99, 101; 100, identifier:_utinfo; 101, string:'wrap_name'; 102, identifier:wrap_name; 103, expression_statement; 103, 104; 104, assignment; 104, 105; 104, 108; 105, subscript; 105, 106; 105, 107; 106, identifier:_utinfo; 107, string:'orig_name'; 108, identifier:orig_name; 109, expression_statement; 109, 110; 110, assignment; 110, 111; 110, 114; 111, subscript; 111, 112; 111, 113; 112, identifier:_utinfo; 113, string:'orig_argspec'; 114, identifier:orig_argspec; 115, if_statement; 115, 116; 115, 121; 116, call; 116, 117; 116, 118; 117, identifier:hasattr; 118, argument_list; 118, 119; 118, 120; 119, identifier:wrapper; 120, string:'_utinfo'; 121, block; 121, 122; 121, 128; 122, expression_statement; 122, 123; 123, assignment; 123, 124; 123, 125; 124, identifier:parent_wrapper_utinfo; 125, attribute; 125, 126; 125, 127; 126, identifier:wrapper; 127, identifier:_utinfo; 128, expression_statement; 128, 129; 129, assignment; 129, 130; 129, 133; 130, subscript; 130, 131; 130, 132; 131, identifier:_utinfo; 132, string:'parent_wrapper_utinfo'; 133, identifier:parent_wrapper_utinfo; 134, if_statement; 134, 135; 134, 140; 135, call; 135, 136; 135, 137; 136, identifier:hasattr; 137, argument_list; 137, 138; 137, 139; 138, identifier:orig_func; 139, string:'_utinfo'; 140, block; 140, 141; 140, 147; 141, expression_statement; 141, 142; 142, assignment; 142, 143; 142, 144; 143, identifier:parent_orig_utinfo; 144, attribute; 144, 145; 144, 146; 145, identifier:orig_func; 146, identifier:_utinfo; 147, expression_statement; 147, 148; 148, assignment; 148, 149; 148, 152; 149, subscript; 149, 150; 149, 151; 150, identifier:_utinfo; 151, string:'parent_orig_utinfo'; 152, identifier:parent_orig_utinfo; 153, comment; 154, comment; 155, expression_statement; 155, 156; 156, assignment; 156, 157; 156, 158; 157, identifier:building_docs; 158, comparison_operator:==; 158, 159; 158, 168; 159, call; 159, 160; 159, 165; 160, attribute; 160, 161; 160, 164; 161, attribute; 161, 162; 161, 163; 162, identifier:os; 163, identifier:environ; 164, identifier:get; 165, argument_list; 165, 166; 165, 167; 166, string:'UTOOL_AUTOGEN_SPHINX_RUNNING'; 167, string:'OFF'; 168, string:'ON'; 169, if_statement; 169, 170; 169, 175; 169, 176; 169, 318; 170, boolean_operator:or; 170, 171; 170, 174; 171, boolean_operator:or; 171, 172; 171, 173; 172, identifier:force; 173, identifier:SIG_PRESERVE; 174, identifier:building_docs; 175, comment; 176, block; 176, 177; 176, 181; 176, 182; 176, 189; 176, 193; 176, 194; 176, 195; 176, 196; 176, 197; 176, 198; 176, 199; 176, 208; 176, 216; 176, 226; 176, 241; 176, 242; 176, 243; 176, 244; 176, 259; 176, 274; 176, 275; 176, 276; 176, 277; 176, 286; 176, 295; 176, 296; 176, 297; 176, 309; 176, 310; 176, 316; 176, 317; 177, expression_statement; 177, 178; 178, assignment; 178, 179; 178, 180; 179, identifier:src_fmt; 180, comment; 181, comment; 182, expression_statement; 182, 183; 183, assignment; 183, 184; 183, 185; 184, identifier:globals_; 185, dictionary; 185, 186; 186, pair; 186, 187; 186, 188; 187, string:'wrapper'; 188, identifier:wrapper; 189, expression_statement; 189, 190; 190, assignment; 190, 191; 190, 192; 191, identifier:locals_; 192, dictionary; 193, comment; 194, comment; 195, comment; 196, comment; 197, comment; 198, comment; 199, expression_statement; 199, 200; 200, assignment; 200, 201; 200, 202; 201, identifier:argspec; 202, call; 202, 203; 202, 206; 203, attribute; 203, 204; 203, 205; 204, identifier:inspect; 205, identifier:getargspec; 206, argument_list; 206, 207; 207, identifier:orig_func; 208, expression_statement; 208, 209; 209, assignment; 209, 210; 209, 215; 210, tuple_pattern; 210, 211; 210, 212; 210, 213; 210, 214; 211, identifier:args; 212, identifier:varargs; 213, identifier:varkw; 214, identifier:defaults; 215, identifier:argspec; 216, expression_statement; 216, 217; 217, assignment; 217, 218; 217, 219; 218, identifier:defsig; 219, call; 219, 220; 219, 223; 220, attribute; 220, 221; 220, 222; 221, identifier:inspect; 222, identifier:formatargspec; 223, argument_list; 223, 224; 224, list_splat; 224, 225; 225, identifier:argspec; 226, expression_statement; 226, 227; 227, assignment; 227, 228; 227, 229; 228, identifier:callsig; 229, call; 229, 230; 229, 233; 230, attribute; 230, 231; 230, 232; 231, identifier:inspect; 232, identifier:formatargspec; 233, argument_list; 233, 234; 234, list_splat; 234, 235; 235, subscript; 235, 236; 235, 237; 236, identifier:argspec; 237, slice; 237, 238; 237, 239; 237, 240; 238, integer:0; 239, colon; 240, integer:3; 241, comment; 242, comment; 243, comment; 244, expression_statement; 244, 245; 245, assignment; 245, 246; 245, 247; 246, identifier:src_fmtdict; 247, call; 247, 248; 247, 249; 248, identifier:dict; 249, argument_list; 249, 250; 249, 253; 249, 256; 250, keyword_argument; 250, 251; 250, 252; 251, identifier:defsig; 252, identifier:defsig; 253, keyword_argument; 253, 254; 253, 255; 254, identifier:callsig; 255, identifier:callsig; 256, keyword_argument; 256, 257; 256, 258; 257, identifier:orig_docstr; 258, identifier:orig_docstr; 259, expression_statement; 259, 260; 260, assignment; 260, 261; 260, 262; 261, identifier:src; 262, call; 262, 263; 262, 271; 263, attribute; 263, 264; 263, 270; 264, call; 264, 265; 264, 268; 265, attribute; 265, 266; 265, 267; 266, identifier:textwrap; 267, identifier:dedent; 268, argument_list; 268, 269; 269, identifier:src_fmt; 270, identifier:format; 271, argument_list; 271, 272; 272, dictionary_splat; 272, 273; 273, identifier:src_fmtdict; 274, comment; 275, comment; 276, comment; 277, expression_statement; 277, 278; 278, assignment; 278, 279; 278, 280; 279, identifier:code; 280, call; 280, 281; 280, 282; 281, identifier:compile; 282, argument_list; 282, 283; 282, 284; 282, 285; 283, identifier:src; 284, string:'<string>'; 285, string:'exec'; 286, expression_statement; 286, 287; 287, call; 287, 288; 287, 291; 288, attribute; 288, 289; 288, 290; 289, identifier:six; 290, identifier:exec_; 291, argument_list; 291, 292; 291, 293; 291, 294; 292, identifier:code; 293, identifier:globals_; 294, identifier:locals_; 295, comment; 296, comment; 297, expression_statement; 297, 298; 298, assignment; 298, 299; 298, 300; 299, identifier:_wrp_preserve; 300, call; 300, 301; 300, 304; 301, attribute; 301, 302; 301, 303; 302, identifier:functools; 303, identifier:update_wrapper; 304, argument_list; 304, 305; 304, 308; 305, subscript; 305, 306; 305, 307; 306, identifier:locals_; 307, string:'_wrp_preserve'; 308, identifier:orig_func; 309, comment; 310, expression_statement; 310, 311; 311, assignment; 311, 312; 311, 315; 312, subscript; 312, 313; 312, 314; 313, identifier:_utinfo; 314, string:'src'; 315, identifier:src; 316, comment; 317, comment; 318, else_clause; 318, 319; 318, 320; 318, 321; 318, 322; 319, comment; 320, comment; 321, comment; 322, block; 322, 323; 322, 333; 323, expression_statement; 323, 324; 324, assignment; 324, 325; 324, 326; 325, identifier:_wrp_preserve; 326, call; 326, 327; 326, 330; 327, attribute; 327, 328; 327, 329; 328, identifier:functools; 329, identifier:update_wrapper; 330, argument_list; 330, 331; 330, 332; 331, identifier:wrapper; 332, identifier:orig_func; 333, comment; 334, expression_statement; 334, 335; 335, assignment; 335, 336; 335, 337; 336, identifier:DEBUG_WRAPPED_DOCSTRING; 337, False; 338, if_statement; 338, 339; 338, 340; 338, 350; 339, identifier:DEBUG_WRAPPED_DOCSTRING; 340, block; 340, 341; 341, expression_statement; 341, 342; 342, assignment; 342, 343; 342, 344; 343, identifier:new_docstr_fmtstr; 344, call; 344, 345; 344, 348; 345, attribute; 345, 346; 345, 347; 346, identifier:util_str; 347, identifier:codeblock; 348, argument_list; 348, 349; 349, string:''' Wrapped function {wrap_name}({orig_name}) orig_argspec = {orig_argspec} orig_docstr = {orig_docstr} '''; 350, else_clause; 350, 351; 351, block; 351, 352; 352, expression_statement; 352, 353; 353, assignment; 353, 354; 353, 355; 354, identifier:new_docstr_fmtstr; 355, call; 355, 356; 355, 359; 356, attribute; 356, 357; 356, 358; 357, identifier:util_str; 358, identifier:codeblock; 359, argument_list; 359, 360; 360, string:''' {orig_docstr} '''; 361, expression_statement; 361, 362; 362, assignment; 362, 363; 362, 364; 363, identifier:new_docstr; 364, call; 364, 365; 364, 368; 365, attribute; 365, 366; 365, 367; 366, identifier:new_docstr_fmtstr; 367, identifier:format; 368, argument_list; 368, 369; 368, 372; 368, 375; 368, 378; 369, keyword_argument; 369, 370; 369, 371; 370, identifier:wrap_name; 371, identifier:wrap_name; 372, keyword_argument; 372, 373; 372, 374; 373, identifier:orig_name; 374, identifier:orig_name; 375, keyword_argument; 375, 376; 375, 377; 376, identifier:orig_docstr; 377, identifier:orig_docstr; 378, keyword_argument; 378, 379; 378, 380; 379, identifier:orig_argspec; 380, identifier:orig_argspec; 381, expression_statement; 381, 382; 382, call; 382, 383; 382, 386; 383, attribute; 383, 384; 383, 385; 384, identifier:meta_util_six; 385, identifier:set_funcdoc; 386, argument_list; 386, 387; 386, 388; 387, identifier:_wrp_preserve; 388, identifier:new_docstr; 389, expression_statement; 389, 390; 390, assignment; 390, 391; 390, 394; 391, attribute; 391, 392; 391, 393; 392, identifier:_wrp_preserve; 393, identifier:_utinfo; 394, identifier:_utinfo; 395, return_statement; 395, 396; 396, identifier:_wrp_preserve
def preserve_sig(wrapper, orig_func, force=False): """ Decorates a wrapper function. It seems impossible to presever signatures in python 2 without eval (Maybe another option is to write to a temporary module?) Args: wrapper: the function wrapping orig_func to change the signature of orig_func: the original function to take the signature from References: http://emptysqua.re/blog/copying-a-python-functions-signature/ https://code.google.com/p/micheles/source/browse/decorator/src/decorator.py TODO: checkout funcsigs https://funcsigs.readthedocs.org/en/latest/ CommandLine: python -m utool.util_decor --test-preserve_sig Example: >>> # ENABLE_DOCTEST >>> import utool as ut >>> #ut.rrrr(False) >>> def myfunction(self, listinput_, arg1, *args, **kwargs): >>> " just a test function " >>> return [x + 1 for x in listinput_] >>> #orig_func = ut.take >>> orig_func = myfunction >>> wrapper = ut.accepts_scalar_input2([0])(orig_func) >>> _wrp_preserve1 = ut.preserve_sig(wrapper, orig_func, True) >>> _wrp_preserve2 = ut.preserve_sig(wrapper, orig_func, False) >>> print('_wrp_preserve2 = %r' % (_wrp_preserve1,)) >>> print('_wrp_preserve2 = %r' % (_wrp_preserve2,)) >>> #print('source _wrp_preserve1 = %s' % (ut.get_func_sourcecode(_wrp_preserve1),)) >>> #print('source _wrp_preserve2 = %s' % (ut.get_func_sourcecode(_wrp_preserve2)),) >>> result = str(_wrp_preserve1) >>> print(result) """ #if True: # import functools # return functools.wraps(orig_func)(wrapper) from utool._internal import meta_util_six from utool import util_str from utool import util_inspect if wrapper is orig_func: # nothing to do return orig_func orig_docstr = meta_util_six.get_funcdoc(orig_func) orig_docstr = '' if orig_docstr is None else orig_docstr orig_argspec = util_inspect.get_func_argspec(orig_func) wrap_name = meta_util_six.get_funccode(wrapper).co_name orig_name = meta_util_six.get_funcname(orig_func) # At the very least preserve info in a dictionary _utinfo = {} _utinfo['orig_func'] = orig_func _utinfo['wrap_name'] = wrap_name _utinfo['orig_name'] = orig_name _utinfo['orig_argspec'] = orig_argspec if hasattr(wrapper, '_utinfo'): parent_wrapper_utinfo = wrapper._utinfo _utinfo['parent_wrapper_utinfo'] = parent_wrapper_utinfo if hasattr(orig_func, '_utinfo'): parent_orig_utinfo = orig_func._utinfo _utinfo['parent_orig_utinfo'] = parent_orig_utinfo # environment variable is set if you are building documentation # preserve sig if building docs building_docs = os.environ.get('UTOOL_AUTOGEN_SPHINX_RUNNING', 'OFF') == 'ON' if force or SIG_PRESERVE or building_docs: # PRESERVES ALL SIGNATURES WITH EXECS src_fmt = r''' def _wrp_preserve{defsig}: """ {orig_docstr} """ try: return wrapper{callsig} except Exception as ex: import utool as ut msg = ('Failure in signature preserving wrapper:\n') ut.printex(ex, msg) raise ''' # Put wrapped function into a scope globals_ = {'wrapper': wrapper} locals_ = {} # argspec is :ArgSpec(args=['bar', 'baz'], varargs=None, keywords=None, # defaults=(True,)) # get orig functions argspec # get functions signature # Get function call signature (no defaults) # Define an exec function argspec = inspect.getargspec(orig_func) (args, varargs, varkw, defaults) = argspec defsig = inspect.formatargspec(*argspec) callsig = inspect.formatargspec(*argspec[0:3]) # TODO: # ut.func_defsig # ut.func_callsig src_fmtdict = dict(defsig=defsig, callsig=callsig, orig_docstr=orig_docstr) src = textwrap.dedent(src_fmt).format(**src_fmtdict) # Define the new function on the fly # (I wish there was a non exec / eval way to do this) #print(src) code = compile(src, '<string>', 'exec') six.exec_(code, globals_, locals_) #six.exec_(src, globals_, locals_) # Use functools.update_wapper to complete preservation _wrp_preserve = functools.update_wrapper(locals_['_wrp_preserve'], orig_func) # Keep debug info _utinfo['src'] = src # Set an internal sig variable that we may use #_wrp_preserve.__sig__ = defsig else: # PRESERVES SOME SIGNATURES NO EXEC # signature preservation is turned off. just preserve the name. # Does not use any exec or eval statments. _wrp_preserve = functools.update_wrapper(wrapper, orig_func) # Just do something to preserve signature DEBUG_WRAPPED_DOCSTRING = False if DEBUG_WRAPPED_DOCSTRING: new_docstr_fmtstr = util_str.codeblock( ''' Wrapped function {wrap_name}({orig_name}) orig_argspec = {orig_argspec} orig_docstr = {orig_docstr} ''' ) else: new_docstr_fmtstr = util_str.codeblock( ''' {orig_docstr} ''' ) new_docstr = new_docstr_fmtstr.format( wrap_name=wrap_name, orig_name=orig_name, orig_docstr=orig_docstr, orig_argspec=orig_argspec) meta_util_six.set_funcdoc(_wrp_preserve, new_docstr) _wrp_preserve._utinfo = _utinfo return _wrp_preserve
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 11; 2, function_name:parse_timestamp; 3, parameters; 3, 4; 3, 5; 3, 8; 4, identifier:timestamp; 5, default_parameter; 5, 6; 5, 7; 6, identifier:zone; 7, string:'UTC'; 8, default_parameter; 8, 9; 8, 10; 9, identifier:timestamp_format; 10, None; 11, block; 11, 12; 11, 14; 11, 21; 11, 29; 11, 42; 11, 60; 11, 61; 11, 83; 11, 105; 11, 106; 11, 110; 11, 182; 11, 194; 11, 243; 11, 369; 12, expression_statement; 12, 13; 13, comment; 14, if_statement; 14, 15; 14, 18; 15, comparison_operator:is; 15, 16; 15, 17; 16, identifier:timestamp; 17, None; 18, block; 18, 19; 19, return_statement; 19, 20; 20, None; 21, expression_statement; 21, 22; 22, assignment; 22, 23; 22, 24; 23, identifier:use_delorean; 24, boolean_operator:or; 24, 25; 24, 26; 25, True; 26, attribute; 26, 27; 26, 28; 27, identifier:six; 28, identifier:PY2; 29, if_statement; 29, 30; 29, 31; 30, identifier:use_delorean; 31, block; 31, 32; 31, 35; 31, 36; 31, 37; 31, 38; 31, 39; 31, 40; 31, 41; 32, import_statement; 32, 33; 33, dotted_name; 33, 34; 34, identifier:delorean; 35, comment; 36, comment; 37, comment; 38, comment; 39, comment; 40, comment; 41, comment; 42, if_statement; 42, 43; 42, 51; 43, not_operator; 43, 44; 44, call; 44, 45; 44, 46; 45, identifier:isinstance; 46, argument_list; 46, 47; 46, 48; 47, identifier:timestamp; 48, attribute; 48, 49; 48, 50; 49, identifier:six; 50, identifier:string_types; 51, block; 51, 52; 52, raise_statement; 52, 53; 53, call; 53, 54; 53, 55; 54, identifier:NotImplementedError; 55, argument_list; 55, 56; 56, binary_operator:%; 56, 57; 56, 58; 57, string:'Unknown format: timestamp=%r'; 58, tuple; 58, 59; 59, identifier:timestamp; 60, comment; 61, if_statement; 61, 62; 61, 65; 61, 66; 61, 77; 62, comparison_operator:is; 62, 63; 62, 64; 63, identifier:timestamp_format; 64, None; 65, comment; 66, block; 66, 67; 67, expression_statement; 67, 68; 68, assignment; 68, 69; 68, 70; 69, identifier:timefmt; 70, call; 70, 71; 70, 72; 71, identifier:determine_timestamp_format; 72, argument_list; 72, 73; 72, 74; 73, identifier:timestamp; 74, keyword_argument; 74, 75; 74, 76; 75, identifier:warn; 76, False; 77, else_clause; 77, 78; 78, block; 78, 79; 79, expression_statement; 79, 80; 80, assignment; 80, 81; 80, 82; 81, identifier:timefmt; 82, identifier:timestamp_format; 83, if_statement; 83, 84; 83, 96; 84, boolean_operator:or; 84, 85; 84, 88; 85, comparison_operator:is; 85, 86; 85, 87; 86, identifier:timefmt; 87, None; 88, not_operator; 88, 89; 89, call; 89, 90; 89, 91; 90, identifier:isinstance; 91, argument_list; 91, 92; 91, 93; 92, identifier:timefmt; 93, attribute; 93, 94; 93, 95; 94, identifier:six; 95, identifier:string_types; 96, block; 96, 97; 97, raise_statement; 97, 98; 98, call; 98, 99; 98, 100; 99, identifier:AssertionError; 100, argument_list; 100, 101; 101, binary_operator:%; 101, 102; 101, 103; 102, string:'unknown timestamp_format=%r'; 103, tuple; 103, 104; 104, identifier:timestamp_format; 105, comment; 106, expression_statement; 106, 107; 107, assignment; 107, 108; 107, 109; 108, identifier:utc_offset; 109, None; 110, if_statement; 110, 111; 110, 121; 110, 141; 110, 176; 111, boolean_operator:and; 111, 112; 111, 118; 112, comparison_operator:==; 112, 113; 112, 117; 113, call; 113, 114; 113, 115; 114, identifier:len; 115, argument_list; 115, 116; 116, identifier:timestamp; 117, integer:20; 118, comparison_operator:in; 118, 119; 118, 120; 119, string:'\x00'; 120, identifier:timestamp; 121, block; 121, 122; 122, expression_statement; 122, 123; 123, assignment; 123, 124; 123, 125; 124, identifier:timestamp_; 125, call; 125, 126; 125, 140; 126, attribute; 126, 127; 126, 139; 127, call; 127, 128; 127, 137; 128, attribute; 128, 129; 128, 136; 129, call; 129, 130; 129, 133; 130, attribute; 130, 131; 130, 132; 131, identifier:timestamp; 132, identifier:replace; 133, argument_list; 133, 134; 133, 135; 134, string:'\x00'; 135, string:' '; 136, identifier:strip; 137, argument_list; 137, 138; 138, string:';'; 139, identifier:strip; 140, argument_list; 141, elif_clause; 141, 142; 141, 150; 142, boolean_operator:and; 142, 143; 142, 144; 143, identifier:use_delorean; 144, comparison_operator:>; 144, 145; 144, 149; 145, call; 145, 146; 145, 147; 146, identifier:len; 147, argument_list; 147, 148; 148, identifier:timestamp; 149, integer:19; 150, block; 150, 151; 150, 168; 151, expression_statement; 151, 152; 152, assignment; 152, 153; 152, 154; 153, identifier:timestamp_; 154, call; 154, 155; 154, 167; 155, attribute; 155, 156; 155, 166; 156, call; 156, 157; 156, 164; 157, attribute; 157, 158; 157, 163; 158, subscript; 158, 159; 158, 160; 159, identifier:timestamp; 160, slice; 160, 161; 160, 162; 161, colon; 162, integer:19; 163, identifier:strip; 164, argument_list; 164, 165; 165, string:';'; 166, identifier:strip; 167, argument_list; 168, expression_statement; 168, 169; 169, assignment; 169, 170; 169, 171; 170, identifier:utc_offset; 171, subscript; 171, 172; 171, 173; 172, identifier:timestamp; 173, slice; 173, 174; 173, 175; 174, integer:19; 175, colon; 176, else_clause; 176, 177; 177, block; 177, 178; 178, expression_statement; 178, 179; 179, assignment; 179, 180; 179, 181; 180, identifier:timestamp_; 181, identifier:timestamp; 182, expression_statement; 182, 183; 183, assignment; 183, 184; 183, 185; 184, identifier:dt_; 185, call; 185, 186; 185, 191; 186, attribute; 186, 187; 186, 190; 187, attribute; 187, 188; 187, 189; 188, identifier:datetime; 189, identifier:datetime; 190, identifier:strptime; 191, argument_list; 191, 192; 191, 193; 192, identifier:timestamp_; 193, identifier:timefmt; 194, if_statement; 194, 195; 194, 196; 194, 197; 194, 198; 194, 199; 194, 200; 194, 237; 195, identifier:use_delorean; 196, comment; 197, comment; 198, comment; 199, comment; 200, block; 200, 201; 200, 214; 200, 227; 201, if_statement; 201, 202; 201, 205; 202, comparison_operator:is; 202, 203; 202, 204; 203, identifier:zone; 204, None; 205, block; 205, 206; 206, expression_statement; 206, 207; 207, assignment; 207, 208; 207, 209; 208, identifier:zone; 209, subscript; 209, 210; 209, 213; 210, attribute; 210, 211; 210, 212; 211, identifier:time; 212, identifier:tzname; 213, integer:0; 214, if_statement; 214, 215; 214, 218; 215, comparison_operator:==; 215, 216; 215, 217; 216, identifier:zone; 217, string:'local'; 218, block; 218, 219; 219, expression_statement; 219, 220; 220, assignment; 220, 221; 220, 222; 221, identifier:zone; 222, subscript; 222, 223; 222, 226; 223, attribute; 223, 224; 223, 225; 224, identifier:time; 225, identifier:tzname; 226, integer:0; 227, expression_statement; 227, 228; 228, assignment; 228, 229; 228, 230; 229, identifier:dn_; 230, call; 230, 231; 230, 234; 231, attribute; 231, 232; 231, 233; 232, identifier:delorean; 233, identifier:Delorean; 234, argument_list; 234, 235; 234, 236; 235, identifier:dt_; 236, identifier:zone; 237, else_clause; 237, 238; 238, block; 238, 239; 239, expression_statement; 239, 240; 240, assignment; 240, 241; 240, 242; 241, identifier:dn_; 242, identifier:dt_; 243, if_statement; 243, 244; 243, 251; 243, 363; 244, boolean_operator:and; 244, 245; 244, 248; 245, comparison_operator:is; 245, 246; 245, 247; 246, identifier:utc_offset; 247, None; 248, comparison_operator:==; 248, 249; 248, 250; 249, identifier:zone; 250, string:'UTC'; 251, block; 251, 252; 252, if_statement; 252, 253; 252, 254; 252, 255; 252, 356; 253, identifier:use_delorean; 254, comment; 255, block; 255, 256; 255, 349; 255, 350; 256, if_statement; 256, 257; 256, 260; 256, 322; 257, comparison_operator:in; 257, 258; 257, 259; 258, string:':'; 259, identifier:utc_offset; 260, block; 260, 261; 260, 281; 260, 296; 260, 316; 261, expression_statement; 261, 262; 262, assignment; 262, 263; 262, 264; 263, identifier:sign; 264, subscript; 264, 265; 264, 278; 265, dictionary; 265, 266; 265, 270; 265, 274; 266, pair; 266, 267; 266, 268; 267, string:' '; 268, unary_operator:+; 268, 269; 269, integer:1; 270, pair; 270, 271; 270, 272; 271, string:'+'; 272, unary_operator:+; 272, 273; 273, integer:1; 274, pair; 274, 275; 274, 276; 275, string:'-'; 276, unary_operator:-; 276, 277; 277, integer:1; 278, subscript; 278, 279; 278, 280; 279, identifier:utc_offset; 280, integer:0; 281, expression_statement; 281, 282; 282, assignment; 282, 283; 282, 286; 283, pattern_list; 283, 284; 283, 285; 284, identifier:hours; 285, identifier:seconds; 286, call; 286, 287; 286, 294; 287, attribute; 287, 288; 287, 293; 288, subscript; 288, 289; 288, 290; 289, identifier:utc_offset; 290, slice; 290, 291; 290, 292; 291, integer:1; 292, colon; 293, identifier:split; 294, argument_list; 294, 295; 295, string:':'; 296, expression_statement; 296, 297; 297, assignment; 297, 298; 297, 299; 298, identifier:delta_; 299, call; 299, 300; 299, 303; 300, attribute; 300, 301; 300, 302; 301, identifier:datetime; 302, identifier:timedelta; 303, argument_list; 303, 304; 303, 310; 304, keyword_argument; 304, 305; 304, 306; 305, identifier:hours; 306, call; 306, 307; 306, 308; 307, identifier:int; 308, argument_list; 308, 309; 309, identifier:hours; 310, keyword_argument; 310, 311; 310, 312; 311, identifier:seconds; 312, call; 312, 313; 312, 314; 313, identifier:int; 314, argument_list; 314, 315; 315, identifier:seconds; 316, expression_statement; 316, 317; 317, assignment; 317, 318; 317, 319; 318, identifier:delta; 319, binary_operator:*; 319, 320; 319, 321; 320, identifier:sign; 321, identifier:delta_; 322, else_clause; 322, 323; 323, block; 323, 324; 323, 327; 323, 335; 324, import_statement; 324, 325; 325, dotted_name; 325, 326; 326, identifier:pytz; 327, expression_statement; 327, 328; 328, assignment; 328, 329; 328, 330; 329, identifier:tzname; 330, call; 330, 331; 330, 334; 331, attribute; 331, 332; 331, 333; 332, identifier:utc_offset; 333, identifier:strip; 334, argument_list; 335, expression_statement; 335, 336; 336, assignment; 336, 337; 336, 338; 337, identifier:delta; 338, call; 338, 339; 338, 347; 339, attribute; 339, 340; 339, 346; 340, call; 340, 341; 340, 344; 341, attribute; 341, 342; 341, 343; 342, identifier:pytz; 343, identifier:timezone; 344, argument_list; 344, 345; 345, identifier:tzname; 346, identifier:utcoffset; 347, argument_list; 347, 348; 348, identifier:dt_; 349, comment; 350, expression_statement; 350, 351; 351, assignment; 351, 352; 351, 353; 352, identifier:dn; 353, binary_operator:-; 353, 354; 353, 355; 354, identifier:dn_; 355, identifier:delta; 356, else_clause; 356, 357; 357, block; 357, 358; 358, raise_statement; 358, 359; 359, call; 359, 360; 359, 361; 360, identifier:AssertionError; 361, argument_list; 361, 362; 362, string:'python3 should take care of timezone'; 363, else_clause; 363, 364; 364, block; 364, 365; 365, expression_statement; 365, 366; 366, assignment; 366, 367; 366, 368; 367, identifier:dn; 368, identifier:dn_; 369, if_statement; 369, 370; 369, 371; 370, identifier:use_delorean; 371, block; 371, 372; 371, 385; 372, if_statement; 372, 373; 372, 377; 373, not_operator; 373, 374; 374, comparison_operator:!=; 374, 375; 374, 376; 375, identifier:zone; 376, string:'UTC'; 377, block; 377, 378; 378, expression_statement; 378, 379; 379, call; 379, 380; 379, 383; 380, attribute; 380, 381; 380, 382; 381, identifier:dn; 382, identifier:shift; 383, argument_list; 383, 384; 384, identifier:zone; 385, return_statement; 385, 386; 386, attribute; 386, 387; 386, 388; 387, identifier:dn; 388, identifier:datetime
def parse_timestamp(timestamp, zone='UTC', timestamp_format=None): r""" pip install delorean Args: timestamp (str): timestampe string zone (bool): assumes input is zone (only if not specified) and gives output in zone. CommandLine: python -m utool.util_time --test-parse_timestamp python -m utool.util_time parse_timestamp Example0: >>> # ENABLE_DOCTEST >>> from utool.util_time import * # NOQA >>> import utool as ut >>> utc = True >>> timestampe_format = None >>> timestamps = [ >>> ('2015:04:01 00:00:00',), >>> ('2005-10-27T14:35:20+02:00',), >>> ('2000-01-01T09:00:00-05:00', 'UTC'), >>> ('2000-01-01T09:00:00-05:00', 'EST'), >>> ('2000-01-01T09:00:00', 'EST'), >>> ('2000-01-01T09:00:00', 'UTC'), >>> ('6:35:01\x002006:03:19 1',), >>> ('2016/08/18 10:51:02 EST',), >>> ('2016-08-18T10:51:02-05:00',), >>> ] >>> timestamp = timestamps[-1][0] >>> dn_list = [parse_timestamp(*args) for args in timestamps] >>> result = ut.NEWLINE.join([str(dn) for dn in dn_list]) >>> print(result) 2015-04-01 00:00:00+00:00 2005-10-27 12:35:20+00:00 2000-01-01 14:00:00+00:00 2000-01-01 09:00:00-05:00 2000-01-01 09:00:00-05:00 2000-01-01 09:00:00+00:00 2006-03-19 06:35:01+00:00 2016-08-18 15:51:02+00:00 2016-08-18 15:51:02+00:00 """ if timestamp is None: return None use_delorean = True or six.PY2 if use_delorean: import delorean ## customize delorean string method #def __str__(self): # return str(self.datetime) # #return str(self.datetime) + ' ' + str(self.timezone) #delorean.Delorean.__str__ = __str__ ## method types must be injected into the class ##ut.inject_func_as_method(dn, __str__, '__repr__', override=True) if not isinstance(timestamp, six.string_types): raise NotImplementedError('Unknown format: timestamp=%r' % (timestamp,)) # Normal format, or non-standard year first data if timestamp_format is None: # dont warn because we will take care of utc timefmt = determine_timestamp_format(timestamp, warn=False) else: timefmt = timestamp_format if timefmt is None or not isinstance(timefmt, six.string_types): raise AssertionError('unknown timestamp_format=%r' % (timestamp_format,)) # Fixup timestamp utc_offset = None if len(timestamp) == 20 and '\x00' in timestamp: timestamp_ = timestamp.replace('\x00', ' ').strip(';').strip() elif use_delorean and len(timestamp) > 19: timestamp_ = timestamp[:19].strip(';').strip() utc_offset = timestamp[19:] else: timestamp_ = timestamp dt_ = datetime.datetime.strptime(timestamp_, timefmt) if use_delorean: #if utc and utc_offset is not None: #if utc: # dn_ = delorean.Delorean(dt_, 'UTC') #else: if zone is None: zone = time.tzname[0] if zone == 'local': zone = time.tzname[0] dn_ = delorean.Delorean(dt_, zone) else: dn_ = dt_ if utc_offset is not None and zone == 'UTC': if use_delorean: # Python 2.7 does not account for timezones if ':' in utc_offset: sign = {' ': +1, '+': +1, '-': -1}[utc_offset[0]] hours, seconds = utc_offset[1:].split(':') delta_ = datetime.timedelta(hours=int(hours), seconds=int(seconds)) delta = sign * delta_ else: import pytz tzname = utc_offset.strip() delta = pytz.timezone(tzname).utcoffset(dt_) # Move back to utc dn = dn_ - delta else: raise AssertionError('python3 should take care of timezone') else: dn = dn_ if use_delorean: if not zone != 'UTC': dn.shift(zone) return dn.datetime
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 16; 2, function_name:load_cache; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 7; 3, 10; 3, 13; 4, identifier:dpath; 5, identifier:fname; 6, identifier:cfgstr; 7, default_parameter; 7, 8; 7, 9; 8, identifier:ext; 9, string:'.cPkl'; 10, default_parameter; 10, 11; 10, 12; 11, identifier:verbose; 12, None; 13, default_parameter; 13, 14; 13, 15; 14, identifier:enabled; 15, True; 16, block; 16, 17; 16, 19; 16, 28; 16, 58; 16, 68; 16, 167; 16, 266; 17, expression_statement; 17, 18; 18, comment; 19, if_statement; 19, 20; 19, 23; 20, comparison_operator:is; 20, 21; 20, 22; 21, identifier:verbose; 22, None; 23, block; 23, 24; 24, expression_statement; 24, 25; 25, assignment; 25, 26; 25, 27; 26, identifier:verbose; 27, identifier:VERBOSE_CACHE; 28, if_statement; 28, 29; 28, 34; 29, boolean_operator:or; 29, 30; 29, 32; 30, not_operator; 30, 31; 31, identifier:USE_CACHE; 32, not_operator; 32, 33; 33, identifier:enabled; 34, block; 34, 35; 34, 52; 35, if_statement; 35, 36; 35, 39; 36, comparison_operator:>; 36, 37; 36, 38; 37, identifier:verbose; 38, integer:1; 39, block; 39, 40; 40, expression_statement; 40, 41; 41, call; 41, 42; 41, 43; 42, identifier:print; 43, argument_list; 43, 44; 44, binary_operator:%; 44, 45; 44, 46; 45, string:'[util_cache] ... cache disabled: dpath=%s cfgstr=%r'; 46, tuple; 46, 47; 46, 51; 47, call; 47, 48; 47, 49; 48, identifier:basename; 49, argument_list; 49, 50; 50, identifier:dpath; 51, identifier:cfgstr; 52, raise_statement; 52, 53; 53, call; 53, 54; 53, 55; 54, identifier:IOError; 55, argument_list; 55, 56; 55, 57; 56, integer:3; 57, string:'Cache Loading Is Disabled'; 58, expression_statement; 58, 59; 59, assignment; 59, 60; 59, 61; 60, identifier:fpath; 61, call; 61, 62; 61, 63; 62, identifier:_args2_fpath; 63, argument_list; 63, 64; 63, 65; 63, 66; 63, 67; 64, identifier:dpath; 65, identifier:fname; 66, identifier:cfgstr; 67, identifier:ext; 68, if_statement; 68, 69; 68, 74; 68, 102; 69, not_operator; 69, 70; 70, call; 70, 71; 70, 72; 71, identifier:exists; 72, argument_list; 72, 73; 73, identifier:fpath; 74, block; 74, 75; 74, 93; 75, if_statement; 75, 76; 75, 79; 76, comparison_operator:>; 76, 77; 76, 78; 77, identifier:verbose; 78, integer:0; 79, block; 79, 80; 80, expression_statement; 80, 81; 81, call; 81, 82; 81, 83; 82, identifier:print; 83, argument_list; 83, 84; 84, binary_operator:%; 84, 85; 84, 86; 85, string:'[util_cache] ... cache does not exist: dpath=%r fname=%r cfgstr=%r'; 86, tuple; 86, 87; 86, 91; 86, 92; 87, call; 87, 88; 87, 89; 88, identifier:basename; 89, argument_list; 89, 90; 90, identifier:dpath; 91, identifier:fname; 92, identifier:cfgstr; 93, raise_statement; 93, 94; 94, call; 94, 95; 94, 96; 95, identifier:IOError; 96, argument_list; 96, 97; 96, 98; 97, integer:2; 98, binary_operator:%; 98, 99; 98, 100; 99, string:'No such file or directory: %r'; 100, tuple; 100, 101; 101, identifier:fpath; 102, else_clause; 102, 103; 103, block; 103, 104; 103, 122; 103, 127; 103, 136; 103, 151; 104, if_statement; 104, 105; 104, 108; 105, comparison_operator:>; 105, 106; 105, 107; 106, identifier:verbose; 107, integer:2; 108, block; 108, 109; 109, expression_statement; 109, 110; 110, call; 110, 111; 110, 112; 111, identifier:print; 112, argument_list; 112, 113; 113, binary_operator:%; 113, 114; 113, 115; 114, string:'[util_cache] ... cache exists: dpath=%r fname=%r cfgstr=%r'; 115, tuple; 115, 116; 115, 120; 115, 121; 116, call; 116, 117; 116, 118; 117, identifier:basename; 118, argument_list; 118, 119; 119, identifier:dpath; 120, identifier:fname; 121, identifier:cfgstr; 122, import_statement; 122, 123; 123, aliased_import; 123, 124; 123, 126; 124, dotted_name; 124, 125; 125, identifier:utool; 126, identifier:ut; 127, expression_statement; 127, 128; 128, assignment; 128, 129; 128, 130; 129, identifier:nbytes; 130, call; 130, 131; 130, 134; 131, attribute; 131, 132; 131, 133; 132, identifier:ut; 133, identifier:get_file_nBytes; 134, argument_list; 134, 135; 135, identifier:fpath; 136, expression_statement; 136, 137; 137, assignment; 137, 138; 137, 139; 138, identifier:big_verbose; 139, boolean_operator:or; 139, 140; 139, 148; 140, parenthesized_expression; 140, 141; 141, boolean_operator:and; 141, 142; 141, 145; 142, comparison_operator:>; 142, 143; 142, 144; 143, identifier:nbytes; 144, float:1E6; 145, comparison_operator:>; 145, 146; 145, 147; 146, identifier:verbose; 147, integer:2; 148, comparison_operator:>; 148, 149; 148, 150; 149, identifier:verbose; 150, integer:2; 151, if_statement; 151, 152; 151, 153; 152, identifier:big_verbose; 153, block; 153, 154; 154, expression_statement; 154, 155; 155, call; 155, 156; 155, 157; 156, identifier:print; 157, argument_list; 157, 158; 158, binary_operator:%; 158, 159; 158, 160; 159, string:'[util_cache] About to read file of size %s'; 160, tuple; 160, 161; 161, call; 161, 162; 161, 165; 162, attribute; 162, 163; 162, 164; 163, identifier:ut; 164, identifier:byte_str2; 165, argument_list; 165, 166; 166, identifier:nbytes; 167, try_statement; 167, 168; 167, 200; 167, 242; 167, 254; 168, block; 168, 169; 169, with_statement; 169, 170; 169, 185; 170, with_clause; 170, 171; 171, with_item; 171, 172; 172, call; 172, 173; 172, 176; 173, attribute; 173, 174; 173, 175; 174, identifier:ut; 175, identifier:Timer; 176, argument_list; 176, 177; 176, 178; 177, identifier:fpath; 178, keyword_argument; 178, 179; 178, 180; 179, identifier:verbose; 180, boolean_operator:and; 180, 181; 180, 182; 181, identifier:big_verbose; 182, comparison_operator:>; 182, 183; 182, 184; 183, identifier:verbose; 184, integer:3; 185, block; 185, 186; 186, expression_statement; 186, 187; 187, assignment; 187, 188; 187, 189; 188, identifier:data; 189, call; 189, 190; 189, 193; 190, attribute; 190, 191; 190, 192; 191, identifier:util_io; 192, identifier:load_data; 193, argument_list; 193, 194; 193, 195; 194, identifier:fpath; 195, keyword_argument; 195, 196; 195, 197; 196, identifier:verbose; 197, comparison_operator:>; 197, 198; 197, 199; 198, identifier:verbose; 199, integer:2; 200, except_clause; 200, 201; 200, 208; 201, as_pattern; 201, 202; 201, 206; 202, tuple; 202, 203; 202, 204; 202, 205; 203, identifier:EOFError; 204, identifier:IOError; 205, identifier:ImportError; 206, as_pattern_target; 206, 207; 207, identifier:ex; 208, block; 208, 209; 208, 217; 208, 234; 209, expression_statement; 209, 210; 210, call; 210, 211; 210, 212; 211, identifier:print; 212, argument_list; 212, 213; 213, binary_operator:%; 213, 214; 213, 215; 214, string:'CORRUPTED? fpath = %s'; 215, tuple; 215, 216; 216, identifier:fpath; 217, if_statement; 217, 218; 217, 221; 218, comparison_operator:>; 218, 219; 218, 220; 219, identifier:verbose; 220, integer:1; 221, block; 221, 222; 222, expression_statement; 222, 223; 223, call; 223, 224; 223, 225; 224, identifier:print; 225, argument_list; 225, 226; 226, binary_operator:%; 226, 227; 226, 228; 227, string:'[util_cache] ... cache miss dpath=%s cfgstr=%r'; 228, tuple; 228, 229; 228, 233; 229, call; 229, 230; 229, 231; 230, identifier:basename; 231, argument_list; 231, 232; 232, identifier:dpath; 233, identifier:cfgstr; 234, raise_statement; 234, 235; 235, call; 235, 236; 235, 237; 236, identifier:IOError; 237, argument_list; 237, 238; 238, call; 238, 239; 238, 240; 239, identifier:str; 240, argument_list; 240, 241; 241, identifier:ex; 242, except_clause; 242, 243; 242, 244; 243, identifier:Exception; 244, block; 244, 245; 244, 253; 245, expression_statement; 245, 246; 246, call; 246, 247; 246, 248; 247, identifier:print; 248, argument_list; 248, 249; 249, binary_operator:%; 249, 250; 249, 251; 250, string:'CORRUPTED? fpath = %s'; 251, tuple; 251, 252; 252, identifier:fpath; 253, raise_statement; 254, else_clause; 254, 255; 255, block; 255, 256; 256, if_statement; 256, 257; 256, 260; 257, comparison_operator:>; 257, 258; 257, 259; 258, identifier:verbose; 259, integer:2; 260, block; 260, 261; 261, expression_statement; 261, 262; 262, call; 262, 263; 262, 264; 263, identifier:print; 264, argument_list; 264, 265; 265, string:'[util_cache] ... cache hit'; 266, return_statement; 266, 267; 267, identifier:data
def load_cache(dpath, fname, cfgstr, ext='.cPkl', verbose=None, enabled=True): """ Loads data using util_io, but smartly constructs a filename """ if verbose is None: verbose = VERBOSE_CACHE if not USE_CACHE or not enabled: if verbose > 1: print('[util_cache] ... cache disabled: dpath=%s cfgstr=%r' % (basename(dpath), cfgstr,)) raise IOError(3, 'Cache Loading Is Disabled') fpath = _args2_fpath(dpath, fname, cfgstr, ext) if not exists(fpath): if verbose > 0: print('[util_cache] ... cache does not exist: dpath=%r fname=%r cfgstr=%r' % ( basename(dpath), fname, cfgstr,)) raise IOError(2, 'No such file or directory: %r' % (fpath,)) else: if verbose > 2: print('[util_cache] ... cache exists: dpath=%r fname=%r cfgstr=%r' % ( basename(dpath), fname, cfgstr,)) import utool as ut nbytes = ut.get_file_nBytes(fpath) big_verbose = (nbytes > 1E6 and verbose > 2) or verbose > 2 if big_verbose: print('[util_cache] About to read file of size %s' % (ut.byte_str2(nbytes),)) try: with ut.Timer(fpath, verbose=big_verbose and verbose > 3): data = util_io.load_data(fpath, verbose=verbose > 2) except (EOFError, IOError, ImportError) as ex: print('CORRUPTED? fpath = %s' % (fpath,)) if verbose > 1: print('[util_cache] ... cache miss dpath=%s cfgstr=%r' % ( basename(dpath), cfgstr,)) raise IOError(str(ex)) except Exception: print('CORRUPTED? fpath = %s' % (fpath,)) raise else: if verbose > 2: print('[util_cache] ... cache hit') return data
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 25; 2, function_name:cached_func; 3, parameters; 3, 4; 3, 7; 3, 10; 3, 13; 3, 16; 3, 19; 3, 22; 4, default_parameter; 4, 5; 4, 6; 5, identifier:fname; 6, None; 7, default_parameter; 7, 8; 7, 9; 8, identifier:cache_dir; 9, string:'default'; 10, default_parameter; 10, 11; 10, 12; 11, identifier:appname; 12, string:'utool'; 13, default_parameter; 13, 14; 13, 15; 14, identifier:key_argx; 15, None; 16, default_parameter; 16, 17; 16, 18; 17, identifier:key_kwds; 18, None; 19, default_parameter; 19, 20; 19, 21; 20, identifier:use_cache; 21, None; 22, default_parameter; 22, 23; 22, 24; 23, identifier:verbose; 24, None; 25, block; 25, 26; 25, 28; 25, 37; 25, 342; 26, expression_statement; 26, 27; 27, comment; 28, if_statement; 28, 29; 28, 32; 29, comparison_operator:is; 29, 30; 29, 31; 30, identifier:verbose; 31, None; 32, block; 32, 33; 33, expression_statement; 33, 34; 34, assignment; 34, 35; 34, 36; 35, identifier:verbose; 36, identifier:VERBOSE_CACHE; 37, function_definition; 37, 38; 37, 39; 37, 41; 38, function_name:cached_closure; 39, parameters; 39, 40; 40, identifier:func; 41, block; 41, 42; 41, 47; 41, 52; 41, 66; 41, 75; 41, 84; 41, 101; 41, 117; 41, 140; 41, 141; 41, 142; 41, 143; 41, 323; 41, 324; 41, 334; 41, 340; 42, import_from_statement; 42, 43; 42, 45; 43, dotted_name; 43, 44; 44, identifier:utool; 45, dotted_name; 45, 46; 46, identifier:util_decor; 47, import_statement; 47, 48; 48, aliased_import; 48, 49; 48, 51; 49, dotted_name; 49, 50; 50, identifier:utool; 51, identifier:ut; 52, expression_statement; 52, 53; 53, assignment; 53, 54; 53, 55; 54, identifier:fname_; 55, conditional_expression:if; 55, 56; 55, 62; 55, 65; 56, call; 56, 57; 56, 60; 57, attribute; 57, 58; 57, 59; 58, identifier:util_inspect; 59, identifier:get_funcname; 60, argument_list; 60, 61; 61, identifier:func; 62, comparison_operator:is; 62, 63; 62, 64; 63, identifier:fname; 64, None; 65, identifier:fname; 66, expression_statement; 66, 67; 67, assignment; 67, 68; 67, 69; 68, identifier:kwdefaults; 69, call; 69, 70; 69, 73; 70, attribute; 70, 71; 70, 72; 71, identifier:util_inspect; 72, identifier:get_kwdefaults; 73, argument_list; 73, 74; 74, identifier:func; 75, expression_statement; 75, 76; 76, assignment; 76, 77; 76, 78; 77, identifier:argnames; 78, call; 78, 79; 78, 82; 79, attribute; 79, 80; 79, 81; 80, identifier:util_inspect; 81, identifier:get_argnames; 82, argument_list; 82, 83; 83, identifier:func; 84, if_statement; 84, 85; 84, 91; 84, 92; 85, call; 85, 86; 85, 89; 86, attribute; 86, 87; 86, 88; 87, identifier:ut; 88, identifier:is_method; 89, argument_list; 89, 90; 90, identifier:func; 91, comment; 92, block; 92, 93; 93, expression_statement; 93, 94; 94, assignment; 94, 95; 94, 96; 95, identifier:argnames; 96, subscript; 96, 97; 96, 98; 97, identifier:argnames; 98, slice; 98, 99; 98, 100; 99, integer:1; 100, colon; 101, expression_statement; 101, 102; 102, assignment; 102, 103; 102, 104; 103, identifier:cacher; 104, call; 104, 105; 104, 106; 105, identifier:Cacher; 106, argument_list; 106, 107; 106, 108; 106, 111; 106, 114; 107, identifier:fname_; 108, keyword_argument; 108, 109; 108, 110; 109, identifier:cache_dir; 110, identifier:cache_dir; 111, keyword_argument; 111, 112; 111, 113; 112, identifier:appname; 113, identifier:appname; 114, keyword_argument; 114, 115; 114, 116; 115, identifier:verbose; 116, identifier:verbose; 117, if_statement; 117, 118; 117, 121; 117, 134; 118, comparison_operator:is; 118, 119; 118, 120; 119, identifier:use_cache; 120, None; 121, block; 121, 122; 122, expression_statement; 122, 123; 123, assignment; 123, 124; 123, 125; 124, identifier:use_cache_; 125, not_operator; 125, 126; 126, call; 126, 127; 126, 130; 127, attribute; 127, 128; 127, 129; 128, identifier:util_arg; 129, identifier:get_argflag; 130, argument_list; 130, 131; 131, binary_operator:+; 131, 132; 131, 133; 132, string:'--nocache-'; 133, identifier:fname_; 134, else_clause; 134, 135; 135, block; 135, 136; 136, expression_statement; 136, 137; 137, assignment; 137, 138; 137, 139; 138, identifier:use_cache_; 139, identifier:use_cache; 140, comment; 141, comment; 142, comment; 143, function_definition; 143, 144; 143, 145; 143, 150; 144, function_name:cached_wraper; 145, parameters; 145, 146; 145, 148; 146, list_splat_pattern; 146, 147; 147, identifier:args; 148, dictionary_splat_pattern; 148, 149; 149, identifier:kwargs; 150, block; 150, 151; 150, 153; 151, expression_statement; 151, 152; 152, comment; 153, try_statement; 153, 154; 153, 261; 153, 262; 153, 263; 154, block; 154, 155; 154, 168; 154, 169; 154, 182; 154, 199; 154, 207; 154, 217; 154, 237; 154, 238; 154, 248; 154, 249; 154, 250; 154, 251; 154, 259; 155, if_statement; 155, 156; 155, 159; 156, comparison_operator:>; 156, 157; 156, 158; 157, identifier:verbose; 158, integer:2; 159, block; 159, 160; 160, expression_statement; 160, 161; 161, call; 161, 162; 161, 163; 162, identifier:print; 163, argument_list; 163, 164; 164, binary_operator:%; 164, 165; 164, 166; 165, string:'[util_cache] computing cached function fname_=%s'; 166, tuple; 166, 167; 167, identifier:fname_; 168, comment; 169, expression_statement; 169, 170; 170, assignment; 170, 171; 170, 172; 171, identifier:cfgstr; 172, call; 172, 173; 172, 174; 173, identifier:get_cfgstr_from_args; 174, argument_list; 174, 175; 174, 176; 174, 177; 174, 178; 174, 179; 174, 180; 174, 181; 175, identifier:func; 176, identifier:args; 177, identifier:kwargs; 178, identifier:key_argx; 179, identifier:key_kwds; 180, identifier:kwdefaults; 181, identifier:argnames; 182, if_statement; 182, 183; 182, 186; 182, 187; 183, attribute; 183, 184; 183, 185; 184, identifier:util_cplat; 185, identifier:WIN32; 186, comment; 187, block; 187, 188; 188, expression_statement; 188, 189; 189, assignment; 189, 190; 189, 191; 190, identifier:cfgstr; 191, binary_operator:+; 191, 192; 191, 193; 192, string:'_'; 193, call; 193, 194; 193, 197; 194, attribute; 194, 195; 194, 196; 195, identifier:util_hash; 196, identifier:hashstr27; 197, argument_list; 197, 198; 198, identifier:cfgstr; 199, assert_statement; 199, 200; 199, 203; 200, comparison_operator:is; 200, 201; 200, 202; 201, identifier:cfgstr; 202, None; 203, binary_operator:%; 203, 204; 203, 205; 204, string:'cfgstr=%r cannot be None'; 205, tuple; 205, 206; 206, identifier:cfgstr; 207, expression_statement; 207, 208; 208, assignment; 208, 209; 208, 210; 209, identifier:use_cache__; 210, call; 210, 211; 210, 214; 211, attribute; 211, 212; 211, 213; 212, identifier:kwargs; 213, identifier:pop; 214, argument_list; 214, 215; 214, 216; 215, string:'use_cache'; 216, identifier:use_cache_; 217, if_statement; 217, 218; 217, 219; 217, 220; 218, identifier:use_cache__; 219, comment; 220, block; 220, 221; 220, 230; 221, expression_statement; 221, 222; 222, assignment; 222, 223; 222, 224; 223, identifier:data; 224, call; 224, 225; 224, 228; 225, attribute; 225, 226; 225, 227; 226, identifier:cacher; 227, identifier:tryload; 228, argument_list; 228, 229; 229, identifier:cfgstr; 230, if_statement; 230, 231; 230, 234; 231, comparison_operator:is; 231, 232; 231, 233; 232, identifier:data; 233, None; 234, block; 234, 235; 235, return_statement; 235, 236; 236, identifier:data; 237, comment; 238, expression_statement; 238, 239; 239, assignment; 239, 240; 239, 241; 240, identifier:data; 241, call; 241, 242; 241, 243; 242, identifier:func; 243, argument_list; 243, 244; 243, 246; 244, list_splat; 244, 245; 245, identifier:args; 246, dictionary_splat; 246, 247; 247, identifier:kwargs; 248, comment; 249, comment; 250, comment; 251, expression_statement; 251, 252; 252, call; 252, 253; 252, 256; 253, attribute; 253, 254; 253, 255; 254, identifier:cacher; 255, identifier:save; 256, argument_list; 256, 257; 256, 258; 257, identifier:data; 258, identifier:cfgstr; 259, return_statement; 259, 260; 260, identifier:data; 261, comment; 262, comment; 263, except_clause; 263, 264; 263, 268; 264, as_pattern; 264, 265; 264, 266; 265, identifier:Exception; 266, as_pattern_target; 266, 267; 267, identifier:ex; 268, block; 268, 269; 268, 274; 268, 295; 268, 314; 268, 322; 269, import_from_statement; 269, 270; 269, 272; 270, dotted_name; 270, 271; 271, identifier:utool; 272, dotted_name; 272, 273; 273, identifier:util_dbg; 274, expression_statement; 274, 275; 275, assignment; 275, 276; 275, 277; 276, identifier:_dbgdict2; 277, call; 277, 278; 277, 279; 278, identifier:dict; 279, argument_list; 279, 280; 279, 283; 279, 289; 280, keyword_argument; 280, 281; 280, 282; 281, identifier:key_argx; 282, identifier:key_argx; 283, keyword_argument; 283, 284; 283, 285; 284, identifier:lenargs; 285, call; 285, 286; 285, 287; 286, identifier:len; 287, argument_list; 287, 288; 288, identifier:args; 289, keyword_argument; 289, 290; 289, 291; 290, identifier:lenkw; 291, call; 291, 292; 291, 293; 292, identifier:len; 293, argument_list; 293, 294; 294, identifier:kwargs; 295, expression_statement; 295, 296; 296, assignment; 296, 297; 296, 298; 297, identifier:msg; 298, call; 298, 299; 298, 302; 299, attribute; 299, 300; 299, 301; 300, string:'\n'; 301, identifier:join; 302, argument_list; 302, 303; 303, list:[ '+--- UTOOL --- ERROR IN CACHED FUNCTION', #'dbgdict = ' + utool.repr4(_dbgdict), 'dbgdict2 = ' + util_str.repr4(_dbgdict2), ]; 303, 304; 303, 305; 303, 306; 304, string:'+--- UTOOL --- ERROR IN CACHED FUNCTION'; 305, comment; 306, binary_operator:+; 306, 307; 306, 308; 307, string:'dbgdict2 = '; 308, call; 308, 309; 308, 312; 309, attribute; 309, 310; 309, 311; 310, identifier:util_str; 311, identifier:repr4; 312, argument_list; 312, 313; 313, identifier:_dbgdict2; 314, expression_statement; 314, 315; 315, call; 315, 316; 315, 319; 316, attribute; 316, 317; 316, 318; 317, identifier:util_dbg; 318, identifier:printex; 319, argument_list; 319, 320; 319, 321; 320, identifier:ex; 321, identifier:msg; 322, raise_statement; 323, comment; 324, expression_statement; 324, 325; 325, assignment; 325, 326; 325, 327; 326, identifier:cached_wraper; 327, call; 327, 328; 327, 331; 328, attribute; 328, 329; 328, 330; 329, identifier:util_decor; 330, identifier:preserve_sig; 331, argument_list; 331, 332; 331, 333; 332, identifier:cached_wraper; 333, identifier:func; 334, expression_statement; 334, 335; 335, assignment; 335, 336; 335, 339; 336, attribute; 336, 337; 336, 338; 337, identifier:cached_wraper; 338, identifier:cacher; 339, identifier:cacher; 340, return_statement; 340, 341; 341, identifier:cached_wraper; 342, return_statement; 342, 343; 343, identifier:cached_closure
def cached_func(fname=None, cache_dir='default', appname='utool', key_argx=None, key_kwds=None, use_cache=None, verbose=None): r""" Wraps a function with a Cacher object uses a hash of arguments as input Args: fname (str): file name (defaults to function name) cache_dir (unicode): (default = u'default') appname (unicode): (default = u'utool') key_argx (None): (default = None) key_kwds (None): (default = None) use_cache (bool): turns on disk based caching(default = None) CommandLine: python -m utool.util_cache --exec-cached_func Example: >>> # ENABLE_DOCTEST >>> import utool as ut >>> def costly_func(a, b, c='d', *args, **kwargs): ... return ([a] * b, c, args, kwargs) >>> ans0 = costly_func(41, 3) >>> ans1 = costly_func(42, 3) >>> closure_ = ut.cached_func('costly_func', appname='utool_test', >>> key_argx=[0, 1]) >>> efficient_func = closure_(costly_func) >>> ans2 = efficient_func(42, 3) >>> ans3 = efficient_func(42, 3) >>> ans4 = efficient_func(41, 3) >>> ans5 = efficient_func(41, 3) >>> assert ans1 == ans2 >>> assert ans2 == ans3 >>> assert ans5 == ans4 >>> assert ans5 == ans0 >>> assert ans1 != ans0 """ if verbose is None: verbose = VERBOSE_CACHE def cached_closure(func): from utool import util_decor import utool as ut fname_ = util_inspect.get_funcname(func) if fname is None else fname kwdefaults = util_inspect.get_kwdefaults(func) argnames = util_inspect.get_argnames(func) if ut.is_method(func): # ignore self for methods argnames = argnames[1:] cacher = Cacher(fname_, cache_dir=cache_dir, appname=appname, verbose=verbose) if use_cache is None: use_cache_ = not util_arg.get_argflag('--nocache-' + fname_) else: use_cache_ = use_cache #_dbgdict = dict(fname_=fname_, key_kwds=key_kwds, appname=appname, # key_argx=key_argx, use_cache_=use_cache_) #@functools.wraps(func) def cached_wraper(*args, **kwargs): """ Cached Wrapper Function Additional Kwargs: use_cache (bool) : enables cache """ try: if verbose > 2: print('[util_cache] computing cached function fname_=%s' % ( fname_,)) # Implicitly adds use_cache to kwargs cfgstr = get_cfgstr_from_args(func, args, kwargs, key_argx, key_kwds, kwdefaults, argnames) if util_cplat.WIN32: # remove potentially invalid chars cfgstr = '_' + util_hash.hashstr27(cfgstr) assert cfgstr is not None, 'cfgstr=%r cannot be None' % (cfgstr,) use_cache__ = kwargs.pop('use_cache', use_cache_) if use_cache__: # Make cfgstr from specified input data = cacher.tryload(cfgstr) if data is not None: return data # Cached missed compute function data = func(*args, **kwargs) # Cache save #if use_cache__: # TODO: save_cache cacher.save(data, cfgstr) return data #except ValueError as ex: # handle protocal error except Exception as ex: from utool import util_dbg _dbgdict2 = dict(key_argx=key_argx, lenargs=len(args), lenkw=len(kwargs),) msg = '\n'.join([ '+--- UTOOL --- ERROR IN CACHED FUNCTION', #'dbgdict = ' + utool.repr4(_dbgdict), 'dbgdict2 = ' + util_str.repr4(_dbgdict2), ]) util_dbg.printex(ex, msg) raise # Give function a handle to the cacher object cached_wraper = util_decor.preserve_sig(cached_wraper, func) cached_wraper.cacher = cacher return cached_wraper return cached_closure
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 15; 2, function_name:path_ndir_split; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 3, 12; 4, identifier:path_; 5, identifier:n; 6, default_parameter; 6, 7; 6, 8; 7, identifier:force_unix; 8, True; 9, default_parameter; 9, 10; 9, 11; 10, identifier:winroot; 11, string:'C:'; 12, default_parameter; 12, 13; 12, 14; 13, identifier:trailing; 14, True; 15, block; 15, 16; 15, 18; 15, 31; 15, 216; 16, expression_statement; 16, 17; 17, comment; 18, if_statement; 18, 19; 18, 27; 18, 28; 19, not_operator; 19, 20; 20, call; 20, 21; 20, 22; 21, identifier:isinstance; 22, argument_list; 22, 23; 22, 24; 23, identifier:path_; 24, attribute; 24, 25; 24, 26; 25, identifier:six; 26, identifier:string_types; 27, comment; 28, block; 28, 29; 29, return_statement; 29, 30; 30, identifier:path_; 31, if_statement; 31, 32; 31, 35; 31, 43; 31, 52; 32, comparison_operator:is; 32, 33; 32, 34; 33, identifier:n; 34, None; 35, block; 35, 36; 36, expression_statement; 36, 37; 37, assignment; 37, 38; 37, 39; 38, identifier:cplat_path; 39, call; 39, 40; 39, 41; 40, identifier:ensure_crossplat_path; 41, argument_list; 41, 42; 42, identifier:path_; 43, elif_clause; 43, 44; 43, 47; 44, comparison_operator:==; 44, 45; 44, 46; 45, identifier:n; 46, integer:0; 47, block; 47, 48; 48, expression_statement; 48, 49; 49, assignment; 49, 50; 49, 51; 50, identifier:cplat_path; 51, string:''; 52, else_clause; 52, 53; 53, block; 53, 54; 53, 63; 53, 67; 53, 71; 53, 75; 53, 145; 53, 181; 53, 196; 53, 203; 53, 204; 54, expression_statement; 54, 55; 55, assignment; 55, 56; 55, 57; 56, identifier:sep; 57, conditional_expression:if; 57, 58; 57, 59; 57, 60; 58, string:'/'; 59, identifier:force_unix; 60, attribute; 60, 61; 60, 62; 61, identifier:os; 62, identifier:sep; 63, expression_statement; 63, 64; 64, assignment; 64, 65; 64, 66; 65, identifier:ndirs_list; 66, list:[]; 67, expression_statement; 67, 68; 68, assignment; 68, 69; 68, 70; 69, identifier:head; 70, identifier:path_; 71, expression_statement; 71, 72; 72, assignment; 72, 73; 72, 74; 73, identifier:reached_end; 74, False; 75, for_statement; 75, 76; 75, 77; 75, 81; 76, identifier:nx; 77, call; 77, 78; 77, 79; 78, identifier:range; 79, argument_list; 79, 80; 80, identifier:n; 81, block; 81, 82; 81, 91; 82, expression_statement; 82, 83; 83, assignment; 83, 84; 83, 87; 84, pattern_list; 84, 85; 84, 86; 85, identifier:head; 86, identifier:tail; 87, call; 87, 88; 87, 89; 88, identifier:split; 89, argument_list; 89, 90; 90, identifier:head; 91, if_statement; 91, 92; 91, 95; 91, 136; 92, comparison_operator:==; 92, 93; 92, 94; 93, identifier:tail; 94, string:''; 95, block; 95, 96; 95, 135; 96, if_statement; 96, 97; 96, 100; 96, 105; 97, comparison_operator:==; 97, 98; 97, 99; 98, identifier:head; 99, string:''; 100, block; 100, 101; 101, expression_statement; 101, 102; 102, assignment; 102, 103; 102, 104; 103, identifier:reached_end; 104, True; 105, else_clause; 105, 106; 106, block; 106, 107; 106, 124; 106, 131; 107, expression_statement; 107, 108; 108, assignment; 108, 109; 108, 110; 109, identifier:root; 110, conditional_expression:if; 110, 111; 110, 112; 110, 118; 111, identifier:head; 112, comparison_operator:==; 112, 113; 112, 117; 113, call; 113, 114; 113, 115; 114, identifier:len; 115, argument_list; 115, 116; 116, identifier:ndirs_list; 117, integer:0; 118, call; 118, 119; 118, 122; 119, attribute; 119, 120; 119, 121; 120, identifier:head; 121, identifier:strip; 122, argument_list; 122, 123; 123, string:'\\/'; 124, expression_statement; 124, 125; 125, call; 125, 126; 125, 129; 126, attribute; 126, 127; 126, 128; 127, identifier:ndirs_list; 128, identifier:append; 129, argument_list; 129, 130; 130, identifier:root; 131, expression_statement; 131, 132; 132, assignment; 132, 133; 132, 134; 133, identifier:reached_end; 134, True; 135, break_statement; 136, else_clause; 136, 137; 137, block; 137, 138; 138, expression_statement; 138, 139; 139, call; 139, 140; 139, 143; 140, attribute; 140, 141; 140, 142; 141, identifier:ndirs_list; 142, identifier:append; 143, argument_list; 143, 144; 144, identifier:tail; 145, if_statement; 145, 146; 145, 150; 146, boolean_operator:and; 146, 147; 146, 148; 147, identifier:trailing; 148, not_operator; 148, 149; 149, identifier:reached_end; 150, block; 150, 151; 150, 160; 151, expression_statement; 151, 152; 152, assignment; 152, 153; 152, 156; 153, pattern_list; 153, 154; 153, 155; 154, identifier:head; 155, identifier:tail; 156, call; 156, 157; 156, 158; 157, identifier:split; 158, argument_list; 158, 159; 159, identifier:head; 160, if_statement; 160, 161; 160, 167; 161, comparison_operator:==; 161, 162; 161, 166; 162, call; 162, 163; 162, 164; 163, identifier:len; 164, argument_list; 164, 165; 165, identifier:tail; 166, integer:0; 167, block; 167, 168; 168, if_statement; 168, 169; 168, 175; 168, 176; 169, comparison_operator:==; 169, 170; 169, 174; 170, call; 170, 171; 170, 172; 171, identifier:len; 172, argument_list; 172, 173; 173, identifier:head; 174, integer:0; 175, comment; 176, block; 176, 177; 177, expression_statement; 177, 178; 178, assignment; 178, 179; 178, 180; 179, identifier:reached_end; 180, True; 181, expression_statement; 181, 182; 182, assignment; 182, 183; 182, 184; 183, identifier:ndirs; 184, call; 184, 185; 184, 188; 185, attribute; 185, 186; 185, 187; 186, identifier:sep; 187, identifier:join; 188, argument_list; 188, 189; 189, subscript; 189, 190; 189, 191; 190, identifier:ndirs_list; 191, slice; 191, 192; 191, 193; 191, 194; 192, colon; 193, colon; 194, unary_operator:-; 194, 195; 195, integer:1; 196, expression_statement; 196, 197; 197, assignment; 197, 198; 197, 199; 198, identifier:cplat_path; 199, call; 199, 200; 199, 201; 200, identifier:ensure_crossplat_path; 201, argument_list; 201, 202; 202, identifier:ndirs; 203, comment; 204, if_statement; 204, 205; 204, 209; 205, boolean_operator:and; 205, 206; 205, 207; 206, identifier:trailing; 207, not_operator; 207, 208; 208, identifier:reached_end; 209, block; 209, 210; 210, expression_statement; 210, 211; 211, assignment; 211, 212; 211, 213; 212, identifier:cplat_path; 213, binary_operator:+; 213, 214; 213, 215; 214, string:'.../'; 215, identifier:cplat_path; 216, return_statement; 216, 217; 217, identifier:cplat_path
def path_ndir_split(path_, n, force_unix=True, winroot='C:', trailing=True): r""" Shows only a little bit of the path. Up to the n bottom-level directories TODO: rename to path_tail? ndir_split? Returns: (str) the trailing n paths of path. CommandLine: python3 -m utool.util_path --test-path_ndir_split python3 -m utool --tf path_ndir_split python -m utool --tf path_ndir_split Example: >>> # ENABLE_DOCTEST >>> from utool.util_path import * # NOQA >>> import utool as ut >>> paths = [r'/usr/bin/local/foo/bar', ... r'C:/', ... #r'lonerel', ... #r'reldir/other', ... r'/ham', ... r'./eggs', ... r'/spam/eggs', ... r'C:\Program Files (x86)/foobar/bin'] >>> N = 2 >>> iter_ = ut.iprod(paths, range(1, N + 1)) >>> force_unix = True >>> tuplist = [(n, path_ndir_split(path_, n)) for path_, n in iter_] >>> chunklist = list(ut.ichunks(tuplist, N)) >>> list_ = [['n=%r: %s' % (x, ut.reprfunc(y)) for x, y in chunk] >>> for chunk in chunklist] >>> line_list = [', '.join(strs) for strs in list_] >>> result = '\n'.join(line_list) >>> print(result) n=1: '.../bar', n=2: '.../foo/bar' n=1: 'C:/', n=2: 'C:/' n=1: '.../ham', n=2: '/ham' n=1: '.../eggs', n=2: './eggs' n=1: '.../eggs', n=2: '.../spam/eggs' n=1: '.../bin', n=2: '.../foobar/bin' """ if not isinstance(path_, six.string_types): # Probably given a file pointer return path_ if n is None: cplat_path = ensure_crossplat_path(path_) elif n == 0: cplat_path = '' else: sep = '/' if force_unix else os.sep ndirs_list = [] head = path_ reached_end = False for nx in range(n): head, tail = split(head) if tail == '': if head == '': reached_end = True else: root = head if len(ndirs_list) == 0 else head.strip('\\/') ndirs_list.append(root) reached_end = True break else: ndirs_list.append(tail) if trailing and not reached_end: head, tail = split(head) if len(tail) == 0: if len(head) == 0: # or head == '/': reached_end = True ndirs = sep.join(ndirs_list[::-1]) cplat_path = ensure_crossplat_path(ndirs) #if trailing and not reached_end: if trailing and not reached_end: cplat_path = '.../' + cplat_path return cplat_path
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 20; 2, function_name:remove_files_in_dir; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 3, 14; 3, 17; 4, identifier:dpath; 5, default_parameter; 5, 6; 5, 7; 6, identifier:fname_pattern_list; 7, string:'*'; 8, default_parameter; 8, 9; 8, 10; 9, identifier:recursive; 10, False; 11, default_parameter; 11, 12; 11, 13; 12, identifier:verbose; 13, identifier:VERBOSE; 14, default_parameter; 14, 15; 14, 16; 15, identifier:dryrun; 16, False; 17, default_parameter; 17, 18; 17, 19; 18, identifier:ignore_errors; 19, False; 20, block; 20, 21; 20, 23; 20, 37; 20, 68; 20, 76; 20, 108; 20, 165; 20, 179; 21, expression_statement; 21, 22; 22, comment; 23, if_statement; 23, 24; 23, 31; 24, call; 24, 25; 24, 26; 25, identifier:isinstance; 26, argument_list; 26, 27; 26, 28; 27, identifier:fname_pattern_list; 28, attribute; 28, 29; 28, 30; 29, identifier:six; 30, identifier:string_types; 31, block; 31, 32; 32, expression_statement; 32, 33; 33, assignment; 33, 34; 33, 35; 34, identifier:fname_pattern_list; 35, list:[fname_pattern_list]; 35, 36; 36, identifier:fname_pattern_list; 37, if_statement; 37, 38; 37, 41; 38, comparison_operator:>; 38, 39; 38, 40; 39, identifier:verbose; 40, integer:2; 41, block; 41, 42; 41, 47; 41, 54; 41, 61; 42, expression_statement; 42, 43; 43, call; 43, 44; 43, 45; 44, identifier:print; 45, argument_list; 45, 46; 46, string:'[util_path] Removing files:'; 47, expression_statement; 47, 48; 48, call; 48, 49; 48, 50; 49, identifier:print; 50, argument_list; 50, 51; 51, binary_operator:%; 51, 52; 51, 53; 52, string:' * from dpath = %r '; 53, identifier:dpath; 54, expression_statement; 54, 55; 55, call; 55, 56; 55, 57; 56, identifier:print; 57, argument_list; 57, 58; 58, binary_operator:%; 58, 59; 58, 60; 59, string:' * with patterns = %r'; 60, identifier:fname_pattern_list; 61, expression_statement; 61, 62; 62, call; 62, 63; 62, 64; 63, identifier:print; 64, argument_list; 64, 65; 65, binary_operator:%; 65, 66; 65, 67; 66, string:' * recursive = %r'; 67, identifier:recursive; 68, expression_statement; 68, 69; 69, assignment; 69, 70; 69, 73; 70, pattern_list; 70, 71; 70, 72; 71, identifier:num_removed; 72, identifier:num_matched; 73, tuple; 73, 74; 73, 75; 74, integer:0; 75, integer:0; 76, if_statement; 76, 77; 76, 82; 77, not_operator; 77, 78; 78, call; 78, 79; 78, 80; 79, identifier:exists; 80, argument_list; 80, 81; 81, identifier:dpath; 82, block; 82, 83; 82, 90; 82, 98; 83, expression_statement; 83, 84; 84, assignment; 84, 85; 84, 86; 85, identifier:msg; 86, parenthesized_expression; 86, 87; 87, binary_operator:%; 87, 88; 87, 89; 88, string:'!!! dir = %r does not exist!'; 89, identifier:dpath; 90, if_statement; 90, 91; 90, 92; 91, identifier:verbose; 92, block; 92, 93; 93, expression_statement; 93, 94; 94, call; 94, 95; 94, 96; 95, identifier:print; 96, argument_list; 96, 97; 97, identifier:msg; 98, expression_statement; 98, 99; 99, call; 99, 100; 99, 103; 100, attribute; 100, 101; 100, 102; 101, identifier:warnings; 102, identifier:warn; 103, argument_list; 103, 104; 103, 105; 104, identifier:msg; 105, keyword_argument; 105, 106; 105, 107; 106, identifier:category; 107, identifier:UserWarning; 108, for_statement; 108, 109; 108, 113; 108, 119; 109, pattern_list; 109, 110; 109, 111; 109, 112; 110, identifier:root; 111, identifier:dname_list; 112, identifier:fname_list; 113, call; 113, 114; 113, 117; 114, attribute; 114, 115; 114, 116; 115, identifier:os; 116, identifier:walk; 117, argument_list; 117, 118; 118, identifier:dpath; 119, block; 119, 120; 119, 160; 120, for_statement; 120, 121; 120, 122; 120, 123; 121, identifier:fname_pattern; 122, identifier:fname_pattern_list; 123, block; 123, 124; 124, for_statement; 124, 125; 124, 126; 124, 133; 125, identifier:fname; 126, call; 126, 127; 126, 130; 127, attribute; 127, 128; 127, 129; 128, identifier:fnmatch; 129, identifier:filter; 130, argument_list; 130, 131; 130, 132; 131, identifier:fname_list; 132, identifier:fname_pattern; 133, block; 133, 134; 133, 138; 134, expression_statement; 134, 135; 135, augmented_assignment:+=; 135, 136; 135, 137; 136, identifier:num_matched; 137, integer:1; 138, expression_statement; 138, 139; 139, augmented_assignment:+=; 139, 140; 139, 141; 140, identifier:num_removed; 141, call; 141, 142; 141, 143; 142, identifier:remove_file; 143, argument_list; 143, 144; 143, 149; 143, 152; 143, 155; 144, call; 144, 145; 144, 146; 145, identifier:join; 146, argument_list; 146, 147; 146, 148; 147, identifier:root; 148, identifier:fname; 149, keyword_argument; 149, 150; 149, 151; 150, identifier:ignore_errors; 151, identifier:ignore_errors; 152, keyword_argument; 152, 153; 152, 154; 153, identifier:dryrun; 154, identifier:dryrun; 155, keyword_argument; 155, 156; 155, 157; 156, identifier:verbose; 157, comparison_operator:>; 157, 158; 157, 159; 158, identifier:verbose; 159, integer:5; 160, if_statement; 160, 161; 160, 163; 161, not_operator; 161, 162; 162, identifier:recursive; 163, block; 163, 164; 164, break_statement; 165, if_statement; 165, 166; 165, 169; 166, comparison_operator:>; 166, 167; 166, 168; 167, identifier:verbose; 168, integer:0; 169, block; 169, 170; 170, expression_statement; 170, 171; 171, call; 171, 172; 171, 173; 172, identifier:print; 173, argument_list; 173, 174; 174, binary_operator:%; 174, 175; 174, 176; 175, string:'[util_path] ... Removed %d/%d files'; 176, tuple; 176, 177; 176, 178; 177, identifier:num_removed; 178, identifier:num_matched; 179, return_statement; 179, 180; 180, True
def remove_files_in_dir(dpath, fname_pattern_list='*', recursive=False, verbose=VERBOSE, dryrun=False, ignore_errors=False): """ Removes files matching a pattern from a directory """ if isinstance(fname_pattern_list, six.string_types): fname_pattern_list = [fname_pattern_list] if verbose > 2: print('[util_path] Removing files:') print(' * from dpath = %r ' % dpath) print(' * with patterns = %r' % fname_pattern_list) print(' * recursive = %r' % recursive) num_removed, num_matched = (0, 0) if not exists(dpath): msg = ('!!! dir = %r does not exist!' % dpath) if verbose: print(msg) warnings.warn(msg, category=UserWarning) for root, dname_list, fname_list in os.walk(dpath): for fname_pattern in fname_pattern_list: for fname in fnmatch.filter(fname_list, fname_pattern): num_matched += 1 num_removed += remove_file(join(root, fname), ignore_errors=ignore_errors, dryrun=dryrun, verbose=verbose > 5) if not recursive: break if verbose > 0: print('[util_path] ... Removed %d/%d files' % (num_removed, num_matched)) return True
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 20; 2, function_name:remove_fpaths; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 3, 14; 3, 17; 4, identifier:fpaths; 5, default_parameter; 5, 6; 5, 7; 6, identifier:verbose; 7, identifier:VERBOSE; 8, default_parameter; 8, 9; 8, 10; 9, identifier:quiet; 10, identifier:QUIET; 11, default_parameter; 11, 12; 11, 13; 12, identifier:strict; 13, False; 14, default_parameter; 14, 15; 14, 16; 15, identifier:print_caller; 16, identifier:PRINT_CALLER; 17, default_parameter; 17, 18; 17, 19; 18, identifier:lbl; 19, string:'files'; 20, block; 20, 21; 20, 23; 20, 28; 20, 47; 20, 54; 20, 66; 20, 78; 20, 82; 20, 97; 20, 104; 20, 105; 20, 192; 20, 205; 21, expression_statement; 21, 22; 22, comment; 23, import_statement; 23, 24; 24, aliased_import; 24, 25; 24, 27; 25, dotted_name; 25, 26; 26, identifier:utool; 27, identifier:ut; 28, if_statement; 28, 29; 28, 30; 29, identifier:print_caller; 30, block; 30, 31; 31, expression_statement; 31, 32; 32, call; 32, 33; 32, 34; 33, identifier:print; 34, argument_list; 34, 35; 35, binary_operator:+; 35, 36; 35, 46; 36, call; 36, 37; 36, 40; 37, attribute; 37, 38; 37, 39; 38, identifier:util_dbg; 39, identifier:get_caller_name; 40, argument_list; 40, 41; 41, call; 41, 42; 41, 43; 42, identifier:range; 43, argument_list; 43, 44; 43, 45; 44, integer:1; 45, integer:4; 46, string:' called remove_fpaths'; 47, expression_statement; 47, 48; 48, assignment; 48, 49; 48, 50; 49, identifier:n_total; 50, call; 50, 51; 50, 52; 51, identifier:len; 52, argument_list; 52, 53; 53, identifier:fpaths; 54, expression_statement; 54, 55; 55, assignment; 55, 56; 55, 57; 56, identifier:_verbose; 57, boolean_operator:or; 57, 58; 57, 65; 58, parenthesized_expression; 58, 59; 59, boolean_operator:and; 59, 60; 59, 62; 60, not_operator; 60, 61; 61, identifier:quiet; 62, comparison_operator:>; 62, 63; 62, 64; 63, identifier:n_total; 64, integer:0; 65, identifier:VERYVERBOSE; 66, if_statement; 66, 67; 66, 68; 67, identifier:_verbose; 68, block; 68, 69; 69, expression_statement; 69, 70; 70, call; 70, 71; 70, 72; 71, identifier:print; 72, argument_list; 72, 73; 73, binary_operator:%; 73, 74; 73, 75; 74, string:'[util_path.remove_fpaths] try removing %d %s'; 75, tuple; 75, 76; 75, 77; 76, identifier:n_total; 77, identifier:lbl; 78, expression_statement; 78, 79; 79, assignment; 79, 80; 79, 81; 80, identifier:n_removed; 81, integer:0; 82, expression_statement; 82, 83; 83, assignment; 83, 84; 83, 85; 84, identifier:prog; 85, call; 85, 86; 85, 89; 86, attribute; 86, 87; 86, 88; 87, identifier:ut; 88, identifier:ProgIter; 89, argument_list; 89, 90; 89, 91; 89, 94; 90, identifier:fpaths; 91, keyword_argument; 91, 92; 91, 93; 92, identifier:label; 93, string:'removing files'; 94, keyword_argument; 94, 95; 94, 96; 95, identifier:enabled; 96, identifier:verbose; 97, expression_statement; 97, 98; 98, assignment; 98, 99; 98, 100; 99, identifier:_iter; 100, call; 100, 101; 100, 102; 101, identifier:iter; 102, argument_list; 102, 103; 103, identifier:prog; 104, comment; 105, try_statement; 105, 106; 105, 122; 106, block; 106, 107; 107, for_statement; 107, 108; 107, 109; 107, 110; 108, identifier:fpath; 109, identifier:_iter; 110, block; 110, 111; 110, 118; 111, expression_statement; 111, 112; 112, call; 112, 113; 112, 116; 113, attribute; 113, 114; 113, 115; 114, identifier:os; 115, identifier:remove; 116, argument_list; 116, 117; 117, identifier:fpath; 118, expression_statement; 118, 119; 119, augmented_assignment:+=; 119, 120; 119, 121; 120, identifier:n_removed; 121, integer:1; 122, except_clause; 122, 123; 122, 127; 122, 128; 123, as_pattern; 123, 124; 123, 125; 124, identifier:OSError; 125, as_pattern_target; 125, 126; 126, identifier:ex; 127, comment; 128, block; 128, 129; 128, 140; 128, 158; 129, if_statement; 129, 130; 129, 131; 130, identifier:VERYVERBOSE; 131, block; 131, 132; 132, expression_statement; 132, 133; 133, call; 133, 134; 133, 135; 134, identifier:print; 135, argument_list; 135, 136; 136, binary_operator:%; 136, 137; 136, 138; 137, string:'WARNING: Could not remove fpath = %r'; 138, tuple; 138, 139; 139, identifier:fpath; 140, if_statement; 140, 141; 140, 142; 141, identifier:strict; 142, block; 142, 143; 142, 157; 143, expression_statement; 143, 144; 144, call; 144, 145; 144, 148; 145, attribute; 145, 146; 145, 147; 146, identifier:util_dbg; 147, identifier:printex; 148, argument_list; 148, 149; 148, 150; 148, 154; 149, identifier:ex; 150, binary_operator:%; 150, 151; 150, 152; 151, string:'Could not remove fpath = %r'; 152, tuple; 152, 153; 153, identifier:fpath; 154, keyword_argument; 154, 155; 154, 156; 155, identifier:iswarning; 156, False; 157, raise_statement; 158, for_statement; 158, 159; 158, 160; 158, 161; 159, identifier:fpath; 160, identifier:_iter; 161, block; 161, 162; 162, try_statement; 162, 163; 162, 175; 163, block; 163, 164; 163, 171; 164, expression_statement; 164, 165; 165, call; 165, 166; 165, 169; 166, attribute; 166, 167; 166, 168; 167, identifier:os; 168, identifier:remove; 169, argument_list; 169, 170; 170, identifier:fpath; 171, expression_statement; 171, 172; 172, augmented_assignment:+=; 172, 173; 172, 174; 173, identifier:n_removed; 174, integer:1; 175, except_clause; 175, 176; 175, 180; 176, as_pattern; 176, 177; 176, 178; 177, identifier:OSError; 178, as_pattern_target; 178, 179; 179, identifier:ex; 180, block; 180, 181; 181, if_statement; 181, 182; 181, 183; 182, identifier:VERYVERBOSE; 183, block; 183, 184; 184, expression_statement; 184, 185; 185, call; 185, 186; 185, 187; 186, identifier:print; 187, argument_list; 187, 188; 188, binary_operator:%; 188, 189; 188, 190; 189, string:'WARNING: Could not remove fpath = %r'; 190, tuple; 190, 191; 191, identifier:fpath; 192, if_statement; 192, 193; 192, 194; 193, identifier:_verbose; 194, block; 194, 195; 195, expression_statement; 195, 196; 196, call; 196, 197; 196, 198; 197, identifier:print; 198, argument_list; 198, 199; 199, binary_operator:%; 199, 200; 199, 201; 200, string:'[util_path.remove_fpaths] ... removed %d / %d %s'; 201, tuple; 201, 202; 201, 203; 201, 204; 202, identifier:n_removed; 203, identifier:n_total; 204, identifier:lbl; 205, return_statement; 205, 206; 206, identifier:n_removed
def remove_fpaths(fpaths, verbose=VERBOSE, quiet=QUIET, strict=False, print_caller=PRINT_CALLER, lbl='files'): """ Removes multiple file paths """ import utool as ut if print_caller: print(util_dbg.get_caller_name(range(1, 4)) + ' called remove_fpaths') n_total = len(fpaths) _verbose = (not quiet and n_total > 0) or VERYVERBOSE if _verbose: print('[util_path.remove_fpaths] try removing %d %s' % (n_total, lbl)) n_removed = 0 prog = ut.ProgIter(fpaths, label='removing files', enabled=verbose) _iter = iter(prog) # Try to be fast at first try: for fpath in _iter: os.remove(fpath) n_removed += 1 except OSError as ex: # Buf if we fail put a try in the inner loop if VERYVERBOSE: print('WARNING: Could not remove fpath = %r' % (fpath,)) if strict: util_dbg.printex(ex, 'Could not remove fpath = %r' % (fpath,), iswarning=False) raise for fpath in _iter: try: os.remove(fpath) n_removed += 1 except OSError as ex: if VERYVERBOSE: print('WARNING: Could not remove fpath = %r' % (fpath,)) if _verbose: print('[util_path.remove_fpaths] ... removed %d / %d %s' % ( n_removed, n_total, lbl)) return n_removed
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 14; 2, function_name:checkpath; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 4, identifier:path_; 5, default_parameter; 5, 6; 5, 7; 6, identifier:verbose; 7, identifier:VERYVERBOSE; 8, default_parameter; 8, 9; 8, 10; 9, identifier:n; 10, None; 11, default_parameter; 11, 12; 11, 13; 12, identifier:info; 13, identifier:VERYVERBOSE; 14, block; 14, 15; 14, 17; 14, 34; 14, 41; 14, 122; 14, 129; 14, 191; 14, 227; 15, expression_statement; 15, 16; 16, comment; 17, assert_statement; 17, 18; 17, 25; 18, call; 18, 19; 18, 20; 19, identifier:isinstance; 20, argument_list; 20, 21; 20, 22; 21, identifier:path_; 22, attribute; 22, 23; 22, 24; 23, identifier:six; 24, identifier:string_types; 25, parenthesized_expression; 25, 26; 26, binary_operator:%; 26, 27; 26, 28; 27, string:'path_=%r is not a string. type(path_) = %r'; 28, tuple; 28, 29; 28, 30; 29, identifier:path_; 30, call; 30, 31; 30, 32; 31, identifier:type; 32, argument_list; 32, 33; 33, identifier:path_; 34, expression_statement; 34, 35; 35, assignment; 35, 36; 35, 37; 36, identifier:path_; 37, call; 37, 38; 37, 39; 38, identifier:normpath; 39, argument_list; 39, 40; 40, identifier:path_; 41, if_statement; 41, 42; 41, 50; 41, 51; 42, call; 42, 43; 42, 48; 43, attribute; 43, 44; 43, 47; 44, attribute; 44, 45; 44, 46; 45, identifier:sys; 46, identifier:platform; 47, identifier:startswith; 48, argument_list; 48, 49; 49, string:'win32'; 50, comment; 51, block; 51, 52; 52, if_statement; 52, 53; 52, 59; 53, call; 53, 54; 53, 57; 54, attribute; 54, 55; 54, 56; 55, identifier:path_; 56, identifier:startswith; 57, argument_list; 57, 58; 58, string:'\\'; 59, block; 59, 60; 59, 69; 60, expression_statement; 60, 61; 61, assignment; 61, 62; 61, 63; 62, identifier:dirs; 63, call; 63, 64; 63, 67; 64, attribute; 64, 65; 64, 66; 65, identifier:path_; 66, identifier:split; 67, argument_list; 67, 68; 68, string:'\\'; 69, if_statement; 69, 70; 69, 94; 70, boolean_operator:and; 70, 71; 70, 86; 71, boolean_operator:and; 71, 72; 71, 78; 72, comparison_operator:>; 72, 73; 72, 77; 73, call; 73, 74; 73, 75; 74, identifier:len; 75, argument_list; 75, 76; 76, identifier:dirs; 77, integer:1; 78, comparison_operator:==; 78, 79; 78, 85; 79, call; 79, 80; 79, 81; 80, identifier:len; 81, argument_list; 81, 82; 82, subscript; 82, 83; 82, 84; 83, identifier:dirs; 84, integer:0; 85, integer:0; 86, comparison_operator:==; 86, 87; 86, 93; 87, call; 87, 88; 87, 89; 88, identifier:len; 89, argument_list; 89, 90; 90, subscript; 90, 91; 90, 92; 91, identifier:dirs; 92, integer:1; 93, integer:1; 94, block; 94, 95; 94, 109; 95, expression_statement; 95, 96; 96, assignment; 96, 97; 96, 100; 97, subscript; 97, 98; 97, 99; 98, identifier:dirs; 99, integer:1; 100, binary_operator:+; 100, 101; 100, 108; 101, call; 101, 102; 101, 107; 102, attribute; 102, 103; 102, 106; 103, subscript; 103, 104; 103, 105; 104, identifier:dirs; 105, integer:1; 106, identifier:upper; 107, argument_list; 108, string:':'; 109, expression_statement; 109, 110; 110, assignment; 110, 111; 110, 112; 111, identifier:path_; 112, call; 112, 113; 112, 116; 113, attribute; 113, 114; 113, 115; 114, string:'\\'; 115, identifier:join; 116, argument_list; 116, 117; 117, subscript; 117, 118; 117, 119; 118, identifier:dirs; 119, slice; 119, 120; 119, 121; 120, integer:1; 121, colon; 122, expression_statement; 122, 123; 123, assignment; 123, 124; 123, 125; 124, identifier:does_exist; 125, call; 125, 126; 125, 127; 126, identifier:exists; 127, argument_list; 127, 128; 128, identifier:path_; 129, if_statement; 129, 130; 129, 131; 129, 132; 130, identifier:verbose; 131, comment; 132, block; 132, 133; 132, 141; 132, 152; 132, 161; 133, expression_statement; 133, 134; 134, assignment; 134, 135; 134, 136; 135, identifier:pretty_path; 136, call; 136, 137; 136, 138; 137, identifier:path_ndir_split; 138, argument_list; 138, 139; 138, 140; 139, identifier:path_; 140, identifier:n; 141, expression_statement; 141, 142; 142, assignment; 142, 143; 142, 144; 143, identifier:caller_name; 144, call; 144, 145; 144, 148; 145, attribute; 145, 146; 145, 147; 146, identifier:util_dbg; 147, identifier:get_caller_name; 148, argument_list; 148, 149; 149, keyword_argument; 149, 150; 149, 151; 150, identifier:allow_genexpr; 151, False; 152, expression_statement; 152, 153; 153, call; 153, 154; 153, 155; 154, identifier:print; 155, argument_list; 155, 156; 156, binary_operator:%; 156, 157; 156, 158; 157, string:'[%s] checkpath(%r)'; 158, tuple; 158, 159; 158, 160; 159, identifier:caller_name; 160, identifier:pretty_path; 161, if_statement; 161, 162; 161, 163; 161, 181; 162, identifier:does_exist; 163, block; 163, 164; 163, 171; 163, 172; 164, expression_statement; 164, 165; 165, assignment; 165, 166; 165, 167; 166, identifier:path_type; 167, call; 167, 168; 167, 169; 168, identifier:get_path_type; 169, argument_list; 169, 170; 170, identifier:path_; 171, comment; 172, expression_statement; 172, 173; 173, call; 173, 174; 173, 175; 174, identifier:print; 175, argument_list; 175, 176; 176, binary_operator:%; 176, 177; 176, 178; 177, string:'[%s] ...(%s) exists'; 178, tuple; 178, 179; 178, 180; 179, identifier:caller_name; 180, identifier:path_type; 181, else_clause; 181, 182; 182, block; 182, 183; 183, expression_statement; 183, 184; 184, call; 184, 185; 184, 186; 185, identifier:print; 186, argument_list; 186, 187; 187, binary_operator:%; 187, 188; 187, 189; 188, string:'[%s] ... does not exist'; 189, parenthesized_expression; 189, 190; 190, identifier:caller_name; 191, if_statement; 191, 192; 191, 196; 191, 197; 192, boolean_operator:and; 192, 193; 192, 195; 193, not_operator; 193, 194; 194, identifier:does_exist; 195, identifier:info; 196, comment; 197, block; 197, 198; 197, 205; 197, 212; 197, 219; 198, expression_statement; 198, 199; 199, assignment; 199, 200; 199, 201; 200, identifier:_longest_path; 201, call; 201, 202; 201, 203; 202, identifier:longest_existing_path; 203, argument_list; 203, 204; 204, identifier:path_; 205, expression_statement; 205, 206; 206, assignment; 206, 207; 206, 208; 207, identifier:_longest_path_type; 208, call; 208, 209; 208, 210; 209, identifier:get_path_type; 210, argument_list; 210, 211; 211, identifier:_longest_path; 212, expression_statement; 212, 213; 213, call; 213, 214; 213, 215; 214, identifier:print; 215, argument_list; 215, 216; 216, binary_operator:%; 216, 217; 216, 218; 217, string:'[util_path] ... The longest existing path is: %r'; 218, identifier:_longest_path; 219, expression_statement; 219, 220; 220, call; 220, 221; 220, 222; 221, identifier:print; 222, argument_list; 222, 223; 223, binary_operator:%; 223, 224; 223, 225; 224, string:'[util_path] ... and has type %r'; 225, tuple; 225, 226; 226, identifier:_longest_path_type; 227, return_statement; 227, 228; 228, identifier:does_exist
def checkpath(path_, verbose=VERYVERBOSE, n=None, info=VERYVERBOSE): r""" verbose wrapper around ``os.path.exists`` Returns: true if ``path_`` exists on the filesystem show only the top `n` directories Args: path_ (str): path string verbose (bool): verbosity flag(default = False) n (int): (default = None) info (bool): (default = False) CommandLine: python -m utool.util_path --test-checkpath Example: >>> # DISABLE_DOCTEST >>> from utool.util_path import * # NOQA >>> import utool as ut >>> path_ = ut.__file__ >>> verbose = True >>> n = None >>> info = False >>> result = checkpath(path_, verbose, n, info) >>> print(result) True Example: >>> # DISABLE_DOCTEST >>> from utool.util_path import * # NOQA >>> import utool as ut >>> path_ = ut.__file__ + 'foobar' >>> verbose = True >>> result = checkpath(path_, verbose, n=None, info=True) >>> print(result) False """ assert isinstance(path_, six.string_types), ( 'path_=%r is not a string. type(path_) = %r' % (path_, type(path_))) path_ = normpath(path_) if sys.platform.startswith('win32'): # convert back to windows style path if using unix style if path_.startswith('\\'): dirs = path_.split('\\') if len(dirs) > 1 and len(dirs[0]) == 0 and len(dirs[1]) == 1: dirs[1] = dirs[1].upper() + ':' path_ = '\\'.join(dirs[1:]) does_exist = exists(path_) if verbose: #print_('[utool] checkpath(%r)' % (path_)) pretty_path = path_ndir_split(path_, n) caller_name = util_dbg.get_caller_name(allow_genexpr=False) print('[%s] checkpath(%r)' % (caller_name, pretty_path)) if does_exist: path_type = get_path_type(path_) #path_type = 'file' if isfile(path_) else 'directory' print('[%s] ...(%s) exists' % (caller_name, path_type,)) else: print('[%s] ... does not exist' % (caller_name)) if not does_exist and info: #print('[util_path] ! Does not exist') _longest_path = longest_existing_path(path_) _longest_path_type = get_path_type(_longest_path) print('[util_path] ... The longest existing path is: %r' % _longest_path) print('[util_path] ... and has type %r' % (_longest_path_type,)) return does_exist
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 28; 2, function_name:glob; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 3, 14; 3, 17; 3, 20; 3, 23; 3, 26; 4, identifier:dpath; 5, default_parameter; 5, 6; 5, 7; 6, identifier:pattern; 7, None; 8, default_parameter; 8, 9; 8, 10; 9, identifier:recursive; 10, False; 11, default_parameter; 11, 12; 11, 13; 12, identifier:with_files; 13, True; 14, default_parameter; 14, 15; 14, 16; 15, identifier:with_dirs; 16, True; 17, default_parameter; 17, 18; 17, 19; 18, identifier:maxdepth; 19, None; 20, default_parameter; 20, 21; 20, 22; 21, identifier:exclude_dirs; 22, list:[]; 23, default_parameter; 23, 24; 23, 25; 24, identifier:fullpath; 25, True; 26, dictionary_splat_pattern; 26, 27; 27, identifier:kwargs; 28, block; 28, 29; 28, 31; 28, 59; 28, 66; 29, expression_statement; 29, 30; 30, comment; 31, expression_statement; 31, 32; 32, assignment; 32, 33; 32, 34; 33, identifier:gen; 34, call; 34, 35; 34, 36; 35, identifier:iglob; 36, argument_list; 36, 37; 36, 38; 36, 39; 36, 42; 36, 45; 36, 48; 36, 51; 36, 54; 36, 57; 37, identifier:dpath; 38, identifier:pattern; 39, keyword_argument; 39, 40; 39, 41; 40, identifier:recursive; 41, identifier:recursive; 42, keyword_argument; 42, 43; 42, 44; 43, identifier:with_files; 44, identifier:with_files; 45, keyword_argument; 45, 46; 45, 47; 46, identifier:with_dirs; 47, identifier:with_dirs; 48, keyword_argument; 48, 49; 48, 50; 49, identifier:maxdepth; 50, identifier:maxdepth; 51, keyword_argument; 51, 52; 51, 53; 52, identifier:fullpath; 53, identifier:fullpath; 54, keyword_argument; 54, 55; 54, 56; 55, identifier:exclude_dirs; 56, identifier:exclude_dirs; 57, dictionary_splat; 57, 58; 58, identifier:kwargs; 59, expression_statement; 59, 60; 60, assignment; 60, 61; 60, 62; 61, identifier:path_list; 62, call; 62, 63; 62, 64; 63, identifier:list; 64, argument_list; 64, 65; 65, identifier:gen; 66, return_statement; 66, 67; 67, identifier:path_list
def glob(dpath, pattern=None, recursive=False, with_files=True, with_dirs=True, maxdepth=None, exclude_dirs=[], fullpath=True, **kwargs): r""" Globs directory for pattern DEPRICATED: use pathlib.glob instead Args: dpath (str): directory path or pattern pattern (str or list): pattern or list of patterns (use only if pattern is not in dpath) recursive (bool): (default = False) with_files (bool): (default = True) with_dirs (bool): (default = True) maxdepth (None): (default = None) exclude_dirs (list): (default = []) Returns: list: path_list SeeAlso: iglob CommandLine: python -m utool.util_path --test-glob python -m utool.util_path --exec-glob:1 Example: >>> # ENABLE_DOCTEST >>> from utool.util_path import * # NOQA >>> from os.path import dirname >>> import utool as ut >>> dpath = dirname(ut.__file__) >>> pattern = '__*.py' >>> recursive = True >>> with_files = True >>> with_dirs = True >>> maxdepth = None >>> fullpath = False >>> exclude_dirs = ['_internal', join(dpath, 'experimental')] >>> print('exclude_dirs = ' + ut.repr2(exclude_dirs)) >>> path_list = glob(dpath, pattern, recursive, with_files, with_dirs, >>> maxdepth, exclude_dirs, fullpath) >>> path_list = sorted(path_list) >>> result = ('path_list = %s' % (ut.repr3(path_list),)) >>> result = result.replace(r'\\', '/') >>> print(result) path_list = [ '__init__.py', '__main__.py', 'tests/__init__.py', ] Example: >>> # DISABLE_DOCTEST >>> from utool.util_path import * # NOQA >>> import utool as ut >>> dpath = dirname(ut.__file__) + '/__*.py' >>> path_list = glob(dpath) >>> result = ('path_list = %s' % (str(path_list),)) >>> print(result) """ gen = iglob(dpath, pattern, recursive=recursive, with_files=with_files, with_dirs=with_dirs, maxdepth=maxdepth, fullpath=fullpath, exclude_dirs=exclude_dirs, **kwargs) path_list = list(gen) return path_list
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 20; 2, function_name:list_images; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 3, 14; 3, 17; 4, identifier:img_dpath_; 5, default_parameter; 5, 6; 5, 7; 6, identifier:ignore_list; 7, list:[]; 8, default_parameter; 8, 9; 8, 10; 9, identifier:recursive; 10, False; 11, default_parameter; 11, 12; 11, 13; 12, identifier:fullpath; 13, False; 14, default_parameter; 14, 15; 14, 16; 15, identifier:full; 16, None; 17, default_parameter; 17, 18; 17, 19; 18, identifier:sort; 19, True; 20, block; 20, 21; 20, 23; 20, 24; 20, 25; 20, 36; 20, 45; 20, 52; 20, 59; 20, 63; 20, 68; 20, 69; 20, 76; 20, 213; 20, 223; 21, expression_statement; 21, 22; 22, comment; 23, comment; 24, comment; 25, if_statement; 25, 26; 25, 29; 26, comparison_operator:is; 26, 27; 26, 28; 27, identifier:full; 28, None; 29, block; 29, 30; 30, expression_statement; 30, 31; 31, assignment; 31, 32; 31, 33; 32, identifier:fullpath; 33, boolean_operator:or; 33, 34; 33, 35; 34, identifier:fullpath; 35, identifier:full; 36, expression_statement; 36, 37; 37, assignment; 37, 38; 37, 39; 38, identifier:img_dpath_; 39, call; 39, 40; 39, 43; 40, attribute; 40, 41; 40, 42; 41, identifier:util_str; 42, identifier:ensure_unicode; 43, argument_list; 43, 44; 44, identifier:img_dpath_; 45, expression_statement; 45, 46; 46, assignment; 46, 47; 46, 48; 47, identifier:img_dpath; 48, call; 48, 49; 48, 50; 49, identifier:realpath; 50, argument_list; 50, 51; 51, identifier:img_dpath_; 52, expression_statement; 52, 53; 53, assignment; 53, 54; 53, 55; 54, identifier:ignore_set; 55, call; 55, 56; 55, 57; 56, identifier:set; 57, argument_list; 57, 58; 58, identifier:ignore_list; 59, expression_statement; 59, 60; 60, assignment; 60, 61; 60, 62; 61, identifier:gname_list_; 62, list:[]; 63, expression_statement; 63, 64; 64, call; 64, 65; 64, 66; 65, identifier:assertpath; 66, argument_list; 66, 67; 67, identifier:img_dpath; 68, comment; 69, expression_statement; 69, 70; 70, assignment; 70, 71; 70, 72; 71, identifier:true_imgpath; 72, call; 72, 73; 72, 74; 73, identifier:truepath; 74, argument_list; 74, 75; 75, identifier:img_dpath; 76, for_statement; 76, 77; 76, 81; 76, 87; 77, pattern_list; 77, 78; 77, 79; 77, 80; 78, identifier:root; 79, identifier:dlist; 80, identifier:flist; 81, call; 81, 82; 81, 85; 82, attribute; 82, 83; 82, 84; 83, identifier:os; 84, identifier:walk; 85, argument_list; 85, 86; 86, identifier:true_imgpath; 87, block; 87, 88; 87, 97; 87, 105; 87, 106; 87, 122; 87, 208; 88, expression_statement; 88, 89; 89, assignment; 89, 90; 89, 91; 90, identifier:root; 91, call; 91, 92; 91, 95; 92, attribute; 92, 93; 92, 94; 93, identifier:util_str; 94, identifier:ensure_unicode; 95, argument_list; 95, 96; 96, identifier:root; 97, expression_statement; 97, 98; 98, assignment; 98, 99; 98, 100; 99, identifier:rel_dpath; 100, call; 100, 101; 100, 102; 101, identifier:relpath; 102, argument_list; 102, 103; 102, 104; 103, identifier:root; 104, identifier:img_dpath; 105, comment; 106, if_statement; 106, 107; 106, 120; 107, call; 107, 108; 107, 109; 108, identifier:any; 109, argument_list; 109, 110; 110, list_comprehension; 110, 111; 110, 114; 111, comparison_operator:in; 111, 112; 111, 113; 112, identifier:dname; 113, identifier:ignore_set; 114, for_in_clause; 114, 115; 114, 116; 115, identifier:dname; 116, call; 116, 117; 116, 118; 117, identifier:dirsplit; 118, argument_list; 118, 119; 119, identifier:rel_dpath; 120, block; 120, 121; 121, continue_statement; 122, for_statement; 122, 123; 122, 124; 122, 128; 123, identifier:fname; 124, call; 124, 125; 124, 126; 125, identifier:iter; 126, argument_list; 126, 127; 127, identifier:flist; 128, block; 128, 129; 128, 138; 128, 152; 128, 168; 129, expression_statement; 129, 130; 130, assignment; 130, 131; 130, 132; 131, identifier:fname; 132, call; 132, 133; 132, 136; 133, attribute; 133, 134; 133, 135; 134, identifier:util_str; 135, identifier:ensure_unicode; 136, argument_list; 136, 137; 137, identifier:fname; 138, expression_statement; 138, 139; 139, assignment; 139, 140; 139, 141; 140, identifier:gname; 141, call; 141, 142; 141, 149; 142, attribute; 142, 143; 142, 148; 143, call; 143, 144; 143, 145; 144, identifier:join; 145, argument_list; 145, 146; 145, 147; 146, identifier:rel_dpath; 147, identifier:fname; 148, identifier:replace; 149, argument_list; 149, 150; 149, 151; 150, string:'\\'; 151, string:'/'; 152, if_statement; 152, 153; 152, 159; 153, call; 153, 154; 153, 157; 154, attribute; 154, 155; 154, 156; 155, identifier:gname; 156, identifier:startswith; 157, argument_list; 157, 158; 158, string:'./'; 159, block; 159, 160; 160, expression_statement; 160, 161; 161, assignment; 161, 162; 161, 163; 162, identifier:gname; 163, subscript; 163, 164; 163, 165; 164, identifier:gname; 165, slice; 165, 166; 165, 167; 166, integer:2; 167, colon; 168, if_statement; 168, 169; 168, 173; 168, 174; 169, call; 169, 170; 169, 171; 170, identifier:fpath_has_imgext; 171, argument_list; 171, 172; 172, identifier:gname; 173, comment; 174, block; 174, 175; 174, 181; 175, if_statement; 175, 176; 175, 179; 176, comparison_operator:in; 176, 177; 176, 178; 177, identifier:gname; 178, identifier:ignore_set; 179, block; 179, 180; 180, continue_statement; 181, if_statement; 181, 182; 181, 183; 181, 199; 182, identifier:fullpath; 183, block; 183, 184; 183, 192; 184, expression_statement; 184, 185; 185, assignment; 185, 186; 185, 187; 186, identifier:gpath; 187, call; 187, 188; 187, 189; 188, identifier:join; 189, argument_list; 189, 190; 189, 191; 190, identifier:img_dpath; 191, identifier:gname; 192, expression_statement; 192, 193; 193, call; 193, 194; 193, 197; 194, attribute; 194, 195; 194, 196; 195, identifier:gname_list_; 196, identifier:append; 197, argument_list; 197, 198; 198, identifier:gpath; 199, else_clause; 199, 200; 200, block; 200, 201; 201, expression_statement; 201, 202; 202, call; 202, 203; 202, 206; 203, attribute; 203, 204; 203, 205; 204, identifier:gname_list_; 205, identifier:append; 206, argument_list; 206, 207; 207, identifier:gname; 208, if_statement; 208, 209; 208, 211; 209, not_operator; 209, 210; 210, identifier:recursive; 211, block; 211, 212; 212, break_statement; 213, if_statement; 213, 214; 213, 215; 214, identifier:sort; 215, block; 215, 216; 216, expression_statement; 216, 217; 217, assignment; 217, 218; 217, 219; 218, identifier:gname_list; 219, call; 219, 220; 219, 221; 220, identifier:sorted; 221, argument_list; 221, 222; 222, identifier:gname_list_; 223, return_statement; 223, 224; 224, identifier:gname_list
def list_images(img_dpath_, ignore_list=[], recursive=False, fullpath=False, full=None, sort=True): r""" Returns a list of images in a directory. By default returns relative paths. TODO: rename to ls_images TODO: Change all instances of fullpath to full Args: img_dpath_ (str): ignore_list (list): (default = []) recursive (bool): (default = False) fullpath (bool): (default = False) full (None): (default = None) sort (bool): (default = True) Returns: list: gname_list CommandLine: python -m utool.util_path --exec-list_images Example: >>> # DISABLE_DOCTEST >>> from utool.util_path import * # NOQA >>> img_dpath_ = '?' >>> ignore_list = [] >>> recursive = False >>> fullpath = False >>> full = None >>> sort = True >>> gname_list = list_images(img_dpath_, ignore_list, recursive, >>> fullpath, full, sort) >>> result = ('gname_list = %s' % (str(gname_list),)) >>> print(result) """ #if not QUIET: # print(ignore_list) if full is not None: fullpath = fullpath or full img_dpath_ = util_str.ensure_unicode(img_dpath_) img_dpath = realpath(img_dpath_) ignore_set = set(ignore_list) gname_list_ = [] assertpath(img_dpath) # Get all the files in a directory recursively true_imgpath = truepath(img_dpath) for root, dlist, flist in os.walk(true_imgpath): root = util_str.ensure_unicode(root) rel_dpath = relpath(root, img_dpath) # Ignore directories if any([dname in ignore_set for dname in dirsplit(rel_dpath)]): continue for fname in iter(flist): fname = util_str.ensure_unicode(fname) gname = join(rel_dpath, fname).replace('\\', '/') if gname.startswith('./'): gname = gname[2:] if fpath_has_imgext(gname): # Ignore Files if gname in ignore_set: continue if fullpath: gpath = join(img_dpath, gname) gname_list_.append(gpath) else: gname_list_.append(gname) if not recursive: break if sort: gname_list = sorted(gname_list_) return gname_list
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 18; 2, function_name:matching_fpaths; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 3, 12; 3, 15; 4, identifier:dpath_list; 5, identifier:include_patterns; 6, default_parameter; 6, 7; 6, 8; 7, identifier:exclude_dirs; 8, list:[]; 9, default_parameter; 9, 10; 9, 11; 10, identifier:greater_exclude_dirs; 11, list:[]; 12, default_parameter; 12, 13; 12, 14; 13, identifier:exclude_patterns; 14, list:[]; 15, default_parameter; 15, 16; 15, 17; 16, identifier:recursive; 17, True; 18, block; 18, 19; 18, 21; 18, 35; 19, expression_statement; 19, 20; 20, comment; 21, if_statement; 21, 22; 21, 29; 22, call; 22, 23; 22, 24; 23, identifier:isinstance; 24, argument_list; 24, 25; 24, 26; 25, identifier:dpath_list; 26, attribute; 26, 27; 26, 28; 27, identifier:six; 28, identifier:string_types; 29, block; 29, 30; 30, expression_statement; 30, 31; 31, assignment; 31, 32; 31, 33; 32, identifier:dpath_list; 33, list:[dpath_list]; 33, 34; 34, identifier:dpath_list; 35, for_statement; 35, 36; 35, 37; 35, 38; 36, identifier:dpath; 37, identifier:dpath_list; 38, block; 38, 39; 39, for_statement; 39, 40; 39, 44; 39, 50; 39, 51; 40, pattern_list; 40, 41; 40, 42; 40, 43; 41, identifier:root; 42, identifier:dname_list; 43, identifier:fname_list; 44, call; 44, 45; 44, 48; 45, attribute; 45, 46; 45, 47; 46, identifier:os; 47, identifier:walk; 48, argument_list; 48, 49; 49, identifier:dpath; 50, comment; 51, block; 51, 52; 51, 63; 51, 64; 51, 77; 51, 78; 51, 87; 51, 93; 51, 137; 52, expression_statement; 52, 53; 53, assignment; 53, 54; 53, 55; 54, identifier:subdirs; 55, call; 55, 56; 55, 57; 56, identifier:pathsplit_full; 57, argument_list; 57, 58; 58, call; 58, 59; 58, 60; 59, identifier:relpath; 60, argument_list; 60, 61; 60, 62; 61, identifier:root; 62, identifier:dpath; 63, comment; 64, if_statement; 64, 65; 64, 75; 65, call; 65, 66; 65, 67; 66, identifier:any; 67, argument_list; 67, 68; 68, list_comprehension; 68, 69; 68, 72; 69, comparison_operator:in; 69, 70; 69, 71; 70, identifier:dir_; 71, identifier:greater_exclude_dirs; 72, for_in_clause; 72, 73; 72, 74; 73, identifier:dir_; 74, identifier:subdirs; 75, block; 75, 76; 76, continue_statement; 77, comment; 78, if_statement; 78, 79; 78, 85; 79, comparison_operator:in; 79, 80; 79, 84; 80, call; 80, 81; 80, 82; 81, identifier:basename; 82, argument_list; 82, 83; 83, identifier:root; 84, identifier:exclude_dirs; 85, block; 85, 86; 86, continue_statement; 87, expression_statement; 87, 88; 88, assignment; 88, 89; 88, 90; 89, identifier:_match; 90, attribute; 90, 91; 90, 92; 91, identifier:fnmatch; 92, identifier:fnmatch; 93, for_statement; 93, 94; 93, 95; 93, 96; 93, 97; 94, identifier:name; 95, identifier:fname_list; 96, comment; 97, block; 97, 98; 98, if_statement; 98, 99; 98, 110; 98, 111; 99, call; 99, 100; 99, 101; 100, identifier:any; 101, generator_expression; 101, 102; 101, 107; 102, call; 102, 103; 102, 104; 103, identifier:_match; 104, argument_list; 104, 105; 104, 106; 105, identifier:name; 106, identifier:pat; 107, for_in_clause; 107, 108; 107, 109; 108, identifier:pat; 109, identifier:include_patterns; 110, comment; 111, block; 111, 112; 112, if_statement; 112, 113; 112, 125; 113, not_operator; 113, 114; 114, call; 114, 115; 114, 116; 115, identifier:any; 116, generator_expression; 116, 117; 116, 122; 117, call; 117, 118; 117, 119; 118, identifier:_match; 119, argument_list; 119, 120; 119, 121; 120, identifier:name; 121, identifier:pat; 122, for_in_clause; 122, 123; 122, 124; 123, identifier:pat; 124, identifier:exclude_patterns; 125, block; 125, 126; 125, 134; 126, expression_statement; 126, 127; 127, assignment; 127, 128; 127, 129; 128, identifier:fpath; 129, call; 129, 130; 129, 131; 130, identifier:join; 131, argument_list; 131, 132; 131, 133; 132, identifier:root; 133, identifier:name; 134, expression_statement; 134, 135; 135, yield; 135, 136; 136, identifier:fpath; 137, if_statement; 137, 138; 137, 140; 138, not_operator; 138, 139; 139, identifier:recursive; 140, block; 140, 141; 141, break_statement
def matching_fpaths(dpath_list, include_patterns, exclude_dirs=[], greater_exclude_dirs=[], exclude_patterns=[], recursive=True): r""" walks dpath lists returning all directories that match the requested pattern. Args: dpath_list (list): include_patterns (str): exclude_dirs (None): recursive (bool): References: # TODO: fix names and behavior of exclude_dirs and greater_exclude_dirs http://stackoverflow.com/questions/19859840/excluding-directories-in-os-walk Example: >>> # DISABLE_DOCTEST >>> from utool.util_path import * # NOQA >>> import utool as ut >>> dpath_list = [dirname(dirname(ut.__file__))] >>> include_patterns = get_standard_include_patterns() >>> exclude_dirs = ['_page'] >>> greater_exclude_dirs = get_standard_exclude_dnames() >>> recursive = True >>> fpath_gen = matching_fpaths(dpath_list, include_patterns, exclude_dirs, >>> greater_exclude_dirs, recursive) >>> result = list(fpath_gen) >>> print('\n'.join(result)) """ if isinstance(dpath_list, six.string_types): dpath_list = [dpath_list] for dpath in dpath_list: for root, dname_list, fname_list in os.walk(dpath): # Look at all subdirs subdirs = pathsplit_full(relpath(root, dpath)) # HACK: if any([dir_ in greater_exclude_dirs for dir_ in subdirs]): continue # Look at one subdir if basename(root) in exclude_dirs: continue _match = fnmatch.fnmatch for name in fname_list: # yeild filepaths that are included if any(_match(name, pat) for pat in include_patterns): # ... and not excluded if not any(_match(name, pat) for pat in exclude_patterns): fpath = join(root, name) yield fpath if not recursive: break
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 27; 2, function_name:sed; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 3, 12; 3, 15; 3, 18; 3, 21; 3, 24; 4, identifier:regexpr; 5, identifier:repl; 6, default_parameter; 6, 7; 6, 8; 7, identifier:force; 8, False; 9, default_parameter; 9, 10; 9, 11; 10, identifier:recursive; 11, False; 12, default_parameter; 12, 13; 12, 14; 13, identifier:dpath_list; 14, None; 15, default_parameter; 15, 16; 15, 17; 16, identifier:fpath_list; 17, None; 18, default_parameter; 18, 19; 18, 20; 19, identifier:verbose; 20, None; 21, default_parameter; 21, 22; 21, 23; 22, identifier:include_patterns; 23, None; 24, default_parameter; 24, 25; 24, 26; 25, identifier:exclude_patterns; 26, list:[]; 27, block; 27, 28; 27, 30; 27, 31; 27, 51; 27, 65; 27, 76; 27, 115; 27, 184; 27, 191; 27, 192; 27, 193; 27, 194; 27, 195; 27, 196; 27, 197; 27, 201; 27, 205; 27, 209; 27, 249; 27, 254; 27, 262; 27, 278; 28, expression_statement; 28, 29; 29, comment; 30, comment; 31, if_statement; 31, 32; 31, 35; 32, comparison_operator:is; 32, 33; 32, 34; 33, identifier:include_patterns; 34, None; 35, block; 35, 36; 36, expression_statement; 36, 37; 37, assignment; 37, 38; 37, 39; 38, identifier:include_patterns; 39, list:['*.py', '*.pyx', '*.pxi', '*.cxx', '*.cpp', '*.hxx', '*.hpp', '*.c', '*.h', '*.html', '*.tex']; 39, 40; 39, 41; 39, 42; 39, 43; 39, 44; 39, 45; 39, 46; 39, 47; 39, 48; 39, 49; 39, 50; 40, string:'*.py'; 41, string:'*.pyx'; 42, string:'*.pxi'; 43, string:'*.cxx'; 44, string:'*.cpp'; 45, string:'*.hxx'; 46, string:'*.hpp'; 47, string:'*.c'; 48, string:'*.h'; 49, string:'*.html'; 50, string:'*.tex'; 51, if_statement; 51, 52; 51, 55; 52, comparison_operator:is; 52, 53; 52, 54; 53, identifier:dpath_list; 54, None; 55, block; 55, 56; 56, expression_statement; 56, 57; 57, assignment; 57, 58; 57, 59; 58, identifier:dpath_list; 59, list:[os.getcwd()]; 59, 60; 60, call; 60, 61; 60, 64; 61, attribute; 61, 62; 61, 63; 62, identifier:os; 63, identifier:getcwd; 64, argument_list; 65, if_statement; 65, 66; 65, 69; 66, comparison_operator:is; 66, 67; 66, 68; 67, identifier:verbose; 68, None; 69, block; 69, 70; 70, expression_statement; 70, 71; 71, assignment; 71, 72; 71, 73; 72, identifier:verbose; 73, attribute; 73, 74; 73, 75; 74, identifier:ut; 75, identifier:NOT_QUIET; 76, if_statement; 76, 77; 76, 80; 76, 109; 77, comparison_operator:is; 77, 78; 77, 79; 78, identifier:fpath_list; 79, None; 80, block; 80, 81; 80, 87; 80, 91; 81, expression_statement; 81, 82; 82, assignment; 82, 83; 82, 84; 83, identifier:greater_exclude_dirs; 84, call; 84, 85; 84, 86; 85, identifier:get_standard_exclude_dnames; 86, argument_list; 87, expression_statement; 87, 88; 88, assignment; 88, 89; 88, 90; 89, identifier:exclude_dirs; 90, list:[]; 91, expression_statement; 91, 92; 92, assignment; 92, 93; 92, 94; 93, identifier:fpath_generator; 94, call; 94, 95; 94, 96; 95, identifier:matching_fpaths; 96, argument_list; 96, 97; 96, 98; 96, 99; 96, 100; 96, 103; 96, 106; 97, identifier:dpath_list; 98, identifier:include_patterns; 99, identifier:exclude_dirs; 100, keyword_argument; 100, 101; 100, 102; 101, identifier:greater_exclude_dirs; 102, identifier:greater_exclude_dirs; 103, keyword_argument; 103, 104; 103, 105; 104, identifier:recursive; 105, identifier:recursive; 106, keyword_argument; 106, 107; 106, 108; 107, identifier:exclude_patterns; 108, identifier:exclude_patterns; 109, else_clause; 109, 110; 110, block; 110, 111; 111, expression_statement; 111, 112; 112, assignment; 112, 113; 112, 114; 113, identifier:fpath_generator; 114, identifier:fpath_list; 115, if_statement; 115, 116; 115, 117; 116, identifier:verbose; 117, block; 117, 118; 117, 126; 117, 134; 117, 142; 117, 150; 117, 158; 117, 166; 117, 171; 118, expression_statement; 118, 119; 119, call; 119, 120; 119, 121; 120, identifier:print; 121, argument_list; 121, 122; 122, binary_operator:%; 122, 123; 122, 124; 123, string:'sed-ing %r'; 124, tuple; 124, 125; 125, identifier:dpath_list; 126, expression_statement; 126, 127; 127, call; 127, 128; 127, 129; 128, identifier:print; 129, argument_list; 129, 130; 130, binary_operator:%; 130, 131; 130, 132; 131, string:' * regular expression : %r'; 132, tuple; 132, 133; 133, identifier:regexpr; 134, expression_statement; 134, 135; 135, call; 135, 136; 135, 137; 136, identifier:print; 137, argument_list; 137, 138; 138, binary_operator:%; 138, 139; 138, 140; 139, string:' * replacement : %r'; 140, tuple; 140, 141; 141, identifier:repl; 142, expression_statement; 142, 143; 143, call; 143, 144; 143, 145; 144, identifier:print; 145, argument_list; 145, 146; 146, binary_operator:%; 146, 147; 146, 148; 147, string:' * include_patterns : %r'; 148, tuple; 148, 149; 149, identifier:include_patterns; 150, expression_statement; 150, 151; 151, call; 151, 152; 151, 153; 152, identifier:print; 153, argument_list; 153, 154; 154, binary_operator:%; 154, 155; 154, 156; 155, string:' * recursive: %r'; 156, tuple; 156, 157; 157, identifier:recursive; 158, expression_statement; 158, 159; 159, call; 159, 160; 159, 161; 160, identifier:print; 161, argument_list; 161, 162; 162, binary_operator:%; 162, 163; 162, 164; 163, string:' * force: %r'; 164, tuple; 164, 165; 165, identifier:force; 166, import_from_statement; 166, 167; 166, 169; 167, dotted_name; 167, 168; 168, identifier:utool; 169, dotted_name; 169, 170; 170, identifier:util_str; 171, expression_statement; 171, 172; 172, call; 172, 173; 172, 174; 173, identifier:print; 174, argument_list; 174, 175; 175, binary_operator:%; 175, 176; 175, 177; 176, string:' * fpath_list: %s'; 177, tuple; 177, 178; 178, call; 178, 179; 178, 182; 179, attribute; 179, 180; 179, 181; 180, identifier:util_str; 181, identifier:repr3; 182, argument_list; 182, 183; 183, identifier:fpath_list; 184, expression_statement; 184, 185; 185, assignment; 185, 186; 185, 187; 186, identifier:regexpr; 187, call; 187, 188; 187, 189; 188, identifier:extend_regex; 189, argument_list; 189, 190; 190, identifier:regexpr; 191, comment; 192, comment; 193, comment; 194, comment; 195, comment; 196, comment; 197, expression_statement; 197, 198; 198, assignment; 198, 199; 198, 200; 199, identifier:num_changed; 200, integer:0; 201, expression_statement; 201, 202; 202, assignment; 202, 203; 202, 204; 203, identifier:num_files_checked; 204, integer:0; 205, expression_statement; 205, 206; 206, assignment; 206, 207; 206, 208; 207, identifier:fpaths_changed; 208, list:[]; 209, for_statement; 209, 210; 209, 211; 209, 212; 210, identifier:fpath; 211, identifier:fpath_generator; 212, block; 212, 213; 212, 217; 212, 230; 213, expression_statement; 213, 214; 214, augmented_assignment:+=; 214, 215; 214, 216; 215, identifier:num_files_checked; 216, integer:1; 217, expression_statement; 217, 218; 218, assignment; 218, 219; 218, 220; 219, identifier:changed_lines; 220, call; 220, 221; 220, 222; 221, identifier:sedfile; 222, argument_list; 222, 223; 222, 224; 222, 225; 222, 226; 222, 227; 223, identifier:fpath; 224, identifier:regexpr; 225, identifier:repl; 226, identifier:force; 227, keyword_argument; 227, 228; 227, 229; 228, identifier:verbose; 229, identifier:verbose; 230, if_statement; 230, 231; 230, 234; 231, comparison_operator:is; 231, 232; 231, 233; 232, identifier:changed_lines; 233, None; 234, block; 234, 235; 234, 242; 235, expression_statement; 235, 236; 236, call; 236, 237; 236, 240; 237, attribute; 237, 238; 237, 239; 238, identifier:fpaths_changed; 239, identifier:append; 240, argument_list; 240, 241; 241, identifier:fpath; 242, expression_statement; 242, 243; 243, augmented_assignment:+=; 243, 244; 243, 245; 244, identifier:num_changed; 245, call; 245, 246; 245, 247; 246, identifier:len; 247, argument_list; 247, 248; 248, identifier:changed_lines; 249, import_statement; 249, 250; 250, aliased_import; 250, 251; 250, 253; 251, dotted_name; 251, 252; 252, identifier:utool; 253, identifier:ut; 254, expression_statement; 254, 255; 255, call; 255, 256; 255, 257; 256, identifier:print; 257, argument_list; 257, 258; 258, binary_operator:%; 258, 259; 258, 260; 259, string:'num_files_checked = %r'; 260, tuple; 260, 261; 261, identifier:num_files_checked; 262, expression_statement; 262, 263; 263, call; 263, 264; 263, 265; 264, identifier:print; 265, argument_list; 265, 266; 266, binary_operator:%; 266, 267; 266, 268; 267, string:'fpaths_changed = %s'; 268, tuple; 268, 269; 269, call; 269, 270; 269, 273; 270, attribute; 270, 271; 270, 272; 271, identifier:ut; 272, identifier:repr3; 273, argument_list; 273, 274; 274, call; 274, 275; 274, 276; 275, identifier:sorted; 276, argument_list; 276, 277; 277, identifier:fpaths_changed; 278, expression_statement; 278, 279; 279, call; 279, 280; 279, 281; 280, identifier:print; 281, argument_list; 281, 282; 282, binary_operator:%; 282, 283; 282, 284; 283, string:'total lines changed = %r'; 284, tuple; 284, 285; 285, identifier:num_changed
def sed(regexpr, repl, force=False, recursive=False, dpath_list=None, fpath_list=None, verbose=None, include_patterns=None, exclude_patterns=[]): """ Python implementation of sed. NOT FINISHED searches and replaces text in files Args: regexpr (str): regx patterns to find repl (str): text to replace force (bool): recursive (bool): dpath_list (list): directories to search (defaults to cwd) """ #_grep(r, [repl], dpath_list=dpath_list, recursive=recursive) if include_patterns is None: include_patterns = ['*.py', '*.pyx', '*.pxi', '*.cxx', '*.cpp', '*.hxx', '*.hpp', '*.c', '*.h', '*.html', '*.tex'] if dpath_list is None: dpath_list = [os.getcwd()] if verbose is None: verbose = ut.NOT_QUIET if fpath_list is None: greater_exclude_dirs = get_standard_exclude_dnames() exclude_dirs = [] fpath_generator = matching_fpaths( dpath_list, include_patterns, exclude_dirs, greater_exclude_dirs=greater_exclude_dirs, recursive=recursive, exclude_patterns=exclude_patterns) else: fpath_generator = fpath_list if verbose: print('sed-ing %r' % (dpath_list,)) print(' * regular expression : %r' % (regexpr,)) print(' * replacement : %r' % (repl,)) print(' * include_patterns : %r' % (include_patterns,)) print(' * recursive: %r' % (recursive,)) print(' * force: %r' % (force,)) from utool import util_str print(' * fpath_list: %s' % (util_str.repr3(fpath_list),)) regexpr = extend_regex(regexpr) #if '\x08' in regexpr: # print('Remember \\x08 != \\b') # print('subsituting for you for you') # regexpr = regexpr.replace('\x08', '\\b') # print(' * regular expression : %r' % (regexpr,)) # Walk through each directory recursively num_changed = 0 num_files_checked = 0 fpaths_changed = [] for fpath in fpath_generator: num_files_checked += 1 changed_lines = sedfile(fpath, regexpr, repl, force, verbose=verbose) if changed_lines is not None: fpaths_changed.append(fpath) num_changed += len(changed_lines) import utool as ut print('num_files_checked = %r' % (num_files_checked,)) print('fpaths_changed = %s' % (ut.repr3(sorted(fpaths_changed)),)) print('total lines changed = %r' % (num_changed,))
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 38; 2, function_name:grep; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 3, 14; 3, 17; 3, 20; 3, 23; 3, 26; 3, 29; 3, 32; 3, 35; 4, identifier:regex_list; 5, default_parameter; 5, 6; 5, 7; 6, identifier:recursive; 7, True; 8, default_parameter; 8, 9; 8, 10; 9, identifier:dpath_list; 10, None; 11, default_parameter; 11, 12; 11, 13; 12, identifier:include_patterns; 13, None; 14, default_parameter; 14, 15; 14, 16; 15, identifier:exclude_dirs; 16, list:[]; 17, default_parameter; 17, 18; 17, 19; 18, identifier:greater_exclude_dirs; 19, None; 20, default_parameter; 20, 21; 20, 22; 21, identifier:inverse; 22, False; 23, default_parameter; 23, 24; 23, 25; 24, identifier:exclude_patterns; 25, list:[]; 26, default_parameter; 26, 27; 26, 28; 27, identifier:verbose; 28, identifier:VERBOSE; 29, default_parameter; 29, 30; 29, 31; 30, identifier:fpath_list; 31, None; 32, default_parameter; 32, 33; 32, 34; 33, identifier:reflags; 34, integer:0; 35, default_parameter; 35, 36; 35, 37; 36, identifier:cache; 37, None; 38, block; 38, 39; 38, 41; 38, 46; 38, 47; 38, 52; 38, 63; 38, 73; 38, 74; 38, 88; 38, 102; 38, 131; 38, 145; 38, 149; 38, 153; 38, 157; 38, 158; 38, 193; 38, 194; 38, 195; 38, 196; 38, 197; 38, 198; 38, 212; 38, 222; 38, 232; 38, 233; 38, 239; 38, 240; 38, 322; 38, 329; 38, 379; 39, expression_statement; 39, 40; 40, comment; 41, import_from_statement; 41, 42; 41, 44; 42, dotted_name; 42, 43; 43, identifier:utool; 44, dotted_name; 44, 45; 45, identifier:util_regex; 46, comment; 47, import_from_statement; 47, 48; 47, 50; 48, dotted_name; 48, 49; 49, identifier:utool; 50, dotted_name; 50, 51; 51, identifier:util_list; 52, if_statement; 52, 53; 52, 56; 53, comparison_operator:is; 53, 54; 53, 55; 54, identifier:include_patterns; 55, None; 56, block; 56, 57; 56, 62; 57, expression_statement; 57, 58; 58, assignment; 58, 59; 58, 60; 59, identifier:include_patterns; 60, list:['*']; 60, 61; 61, string:'*'; 62, comment; 63, if_statement; 63, 64; 63, 67; 64, comparison_operator:is; 64, 65; 64, 66; 65, identifier:greater_exclude_dirs; 66, None; 67, block; 67, 68; 67, 72; 68, expression_statement; 68, 69; 69, assignment; 69, 70; 69, 71; 70, identifier:greater_exclude_dirs; 71, list:[]; 72, comment; 73, comment; 74, if_statement; 74, 75; 74, 82; 75, call; 75, 76; 75, 77; 76, identifier:isinstance; 77, argument_list; 77, 78; 77, 79; 78, identifier:include_patterns; 79, attribute; 79, 80; 79, 81; 80, identifier:six; 81, identifier:string_types; 82, block; 82, 83; 83, expression_statement; 83, 84; 84, assignment; 84, 85; 84, 86; 85, identifier:include_patterns; 86, list:[include_patterns]; 86, 87; 87, identifier:include_patterns; 88, if_statement; 88, 89; 88, 92; 89, comparison_operator:is; 89, 90; 89, 91; 90, identifier:dpath_list; 91, None; 92, block; 92, 93; 93, expression_statement; 93, 94; 94, assignment; 94, 95; 94, 96; 95, identifier:dpath_list; 96, list:[os.getcwd()]; 96, 97; 97, call; 97, 98; 97, 101; 98, attribute; 98, 99; 98, 100; 99, identifier:os; 100, identifier:getcwd; 101, argument_list; 102, if_statement; 102, 103; 102, 104; 103, identifier:verbose; 104, block; 104, 105; 104, 113; 104, 123; 105, expression_statement; 105, 106; 106, assignment; 106, 107; 106, 108; 107, identifier:recursive_stat_str; 108, subscript; 108, 109; 108, 112; 109, list:['flat', 'recursive']; 109, 110; 109, 111; 110, string:'flat'; 111, string:'recursive'; 112, identifier:recursive; 113, expression_statement; 113, 114; 114, call; 114, 115; 114, 116; 115, identifier:print; 116, argument_list; 116, 117; 117, binary_operator:%; 117, 118; 117, 119; 118, string:'[util_path] Greping (%s) %r for %r'; 119, tuple; 119, 120; 119, 121; 119, 122; 120, identifier:recursive_stat_str; 121, identifier:dpath_list; 122, identifier:regex_list; 123, expression_statement; 123, 124; 124, call; 124, 125; 124, 126; 125, identifier:print; 126, argument_list; 126, 127; 127, binary_operator:%; 127, 128; 127, 129; 128, string:'[util_path] regex_list = %s'; 129, parenthesized_expression; 129, 130; 130, identifier:regex_list; 131, if_statement; 131, 132; 131, 139; 132, call; 132, 133; 132, 134; 133, identifier:isinstance; 134, argument_list; 134, 135; 134, 136; 135, identifier:regex_list; 136, attribute; 136, 137; 136, 138; 137, identifier:six; 138, identifier:string_types; 139, block; 139, 140; 140, expression_statement; 140, 141; 141, assignment; 141, 142; 141, 143; 142, identifier:regex_list; 143, list:[regex_list]; 143, 144; 144, identifier:regex_list; 145, expression_statement; 145, 146; 146, assignment; 146, 147; 146, 148; 147, identifier:found_fpath_list; 148, list:[]; 149, expression_statement; 149, 150; 150, assignment; 150, 151; 150, 152; 151, identifier:found_lines_list; 152, list:[]; 153, expression_statement; 153, 154; 154, assignment; 154, 155; 154, 156; 155, identifier:found_lxs_list; 156, list:[]; 157, comment; 158, if_statement; 158, 159; 158, 162; 158, 187; 159, comparison_operator:is; 159, 160; 159, 161; 160, identifier:fpath_list; 161, None; 162, block; 162, 163; 163, expression_statement; 163, 164; 164, assignment; 164, 165; 164, 166; 165, identifier:fpath_generator; 166, call; 166, 167; 166, 168; 167, identifier:matching_fpaths; 168, argument_list; 168, 169; 168, 172; 168, 175; 168, 178; 168, 181; 168, 184; 169, keyword_argument; 169, 170; 169, 171; 170, identifier:dpath_list; 171, identifier:dpath_list; 172, keyword_argument; 172, 173; 172, 174; 173, identifier:include_patterns; 174, identifier:include_patterns; 175, keyword_argument; 175, 176; 175, 177; 176, identifier:exclude_dirs; 177, identifier:exclude_dirs; 178, keyword_argument; 178, 179; 178, 180; 179, identifier:greater_exclude_dirs; 180, identifier:greater_exclude_dirs; 181, keyword_argument; 181, 182; 181, 183; 182, identifier:exclude_patterns; 183, identifier:exclude_patterns; 184, keyword_argument; 184, 185; 184, 186; 185, identifier:recursive; 186, identifier:recursive; 187, else_clause; 187, 188; 188, block; 188, 189; 189, expression_statement; 189, 190; 190, assignment; 190, 191; 190, 192; 191, identifier:fpath_generator; 192, identifier:fpath_list; 193, comment; 194, comment; 195, comment; 196, comment; 197, comment; 198, expression_statement; 198, 199; 199, assignment; 199, 200; 199, 201; 200, identifier:_exprs_flags; 201, list_comprehension; 201, 202; 201, 209; 202, call; 202, 203; 202, 206; 203, attribute; 203, 204; 203, 205; 204, identifier:util_regex; 205, identifier:extend_regex2; 206, argument_list; 206, 207; 206, 208; 207, identifier:expr; 208, identifier:reflags; 209, for_in_clause; 209, 210; 209, 211; 210, identifier:expr; 211, identifier:regex_list; 212, expression_statement; 212, 213; 213, assignment; 213, 214; 213, 215; 214, identifier:extended_regex_list; 215, call; 215, 216; 215, 219; 216, attribute; 216, 217; 216, 218; 217, identifier:util_list; 218, identifier:take_column; 219, argument_list; 219, 220; 219, 221; 220, identifier:_exprs_flags; 221, integer:0; 222, expression_statement; 222, 223; 223, assignment; 223, 224; 223, 225; 224, identifier:reflags_list; 225, call; 225, 226; 225, 229; 226, attribute; 226, 227; 226, 228; 227, identifier:util_list; 228, identifier:take_column; 229, argument_list; 229, 230; 229, 231; 230, identifier:_exprs_flags; 231, integer:1; 232, comment; 233, expression_statement; 233, 234; 234, assignment; 234, 235; 234, 236; 235, identifier:reflags; 236, subscript; 236, 237; 236, 238; 237, identifier:reflags_list; 238, integer:0; 239, comment; 240, for_statement; 240, 241; 240, 242; 240, 243; 240, 244; 241, identifier:fpath; 242, identifier:fpath_generator; 243, comment; 244, block; 244, 245; 244, 259; 245, expression_statement; 245, 246; 246, assignment; 246, 247; 246, 250; 247, pattern_list; 247, 248; 247, 249; 248, identifier:found_lines; 249, identifier:found_lxs; 250, call; 250, 251; 250, 252; 251, identifier:grepfile; 252, argument_list; 252, 253; 252, 254; 252, 255; 252, 256; 253, identifier:fpath; 254, identifier:extended_regex_list; 255, identifier:reflags_list; 256, keyword_argument; 256, 257; 256, 258; 257, identifier:cache; 258, identifier:cache; 259, if_statement; 259, 260; 259, 261; 259, 292; 260, identifier:inverse; 261, block; 261, 262; 262, if_statement; 262, 263; 262, 269; 262, 270; 263, comparison_operator:==; 263, 264; 263, 268; 264, call; 264, 265; 264, 266; 265, identifier:len; 266, argument_list; 266, 267; 267, identifier:found_lines; 268, integer:0; 269, comment; 270, block; 270, 271; 270, 278; 270, 285; 271, expression_statement; 271, 272; 272, call; 272, 273; 272, 276; 273, attribute; 273, 274; 273, 275; 274, identifier:found_fpath_list; 275, identifier:append; 276, argument_list; 276, 277; 277, identifier:fpath; 278, expression_statement; 278, 279; 279, call; 279, 280; 279, 283; 280, attribute; 280, 281; 280, 282; 281, identifier:found_lines_list; 282, identifier:append; 283, argument_list; 283, 284; 284, list:[]; 285, expression_statement; 285, 286; 286, call; 286, 287; 286, 290; 287, attribute; 287, 288; 287, 289; 288, identifier:found_lxs_list; 289, identifier:append; 290, argument_list; 290, 291; 291, list:[]; 292, elif_clause; 292, 293; 292, 299; 293, comparison_operator:>; 293, 294; 293, 298; 294, call; 294, 295; 294, 296; 295, identifier:len; 296, argument_list; 296, 297; 297, identifier:found_lines; 298, integer:0; 299, block; 299, 300; 299, 307; 299, 308; 299, 315; 300, expression_statement; 300, 301; 301, call; 301, 302; 301, 305; 302, attribute; 302, 303; 302, 304; 303, identifier:found_fpath_list; 304, identifier:append; 305, argument_list; 305, 306; 306, identifier:fpath; 307, comment; 308, expression_statement; 308, 309; 309, call; 309, 310; 309, 313; 310, attribute; 310, 311; 310, 312; 311, identifier:found_lines_list; 312, identifier:append; 313, argument_list; 313, 314; 314, identifier:found_lines; 315, expression_statement; 315, 316; 316, call; 316, 317; 316, 320; 317, attribute; 317, 318; 317, 319; 318, identifier:found_lxs_list; 319, identifier:append; 320, argument_list; 320, 321; 321, identifier:found_lxs; 322, expression_statement; 322, 323; 323, assignment; 323, 324; 323, 325; 324, identifier:grep_result; 325, tuple; 325, 326; 325, 327; 325, 328; 326, identifier:found_fpath_list; 327, identifier:found_lines_list; 328, identifier:found_lxs_list; 329, if_statement; 329, 330; 329, 331; 330, identifier:verbose; 331, block; 331, 332; 331, 337; 331, 342; 331, 352; 331, 362; 331, 363; 331, 364; 331, 365; 331, 366; 331, 367; 331, 368; 331, 369; 331, 370; 331, 371; 331, 372; 331, 373; 331, 374; 331, 375; 331, 376; 331, 377; 331, 378; 332, expression_statement; 332, 333; 333, call; 333, 334; 333, 335; 334, identifier:print; 335, argument_list; 335, 336; 336, string:'=========='; 337, expression_statement; 337, 338; 338, call; 338, 339; 338, 340; 339, identifier:print; 340, argument_list; 340, 341; 341, string:'=========='; 342, expression_statement; 342, 343; 343, call; 343, 344; 343, 345; 344, identifier:print; 345, argument_list; 345, 346; 346, binary_operator:%; 346, 347; 346, 348; 347, string:'[util_path] found matches in %d files'; 348, call; 348, 349; 348, 350; 349, identifier:len; 350, argument_list; 350, 351; 351, identifier:found_fpath_list; 352, expression_statement; 352, 353; 353, call; 353, 354; 353, 355; 354, identifier:print; 355, argument_list; 355, 356; 356, call; 356, 357; 356, 358; 357, identifier:make_grep_resultstr; 358, argument_list; 358, 359; 358, 360; 358, 361; 359, identifier:grep_result; 360, identifier:extended_regex_list; 361, identifier:reflags; 362, comment; 363, comment; 364, comment; 365, comment; 366, comment; 367, comment; 368, comment; 369, comment; 370, comment; 371, comment; 372, comment; 373, comment; 374, comment; 375, comment; 376, comment; 377, comment; 378, comment; 379, return_statement; 379, 380; 380, identifier:grep_result
def grep(regex_list, recursive=True, dpath_list=None, include_patterns=None, exclude_dirs=[], greater_exclude_dirs=None, inverse=False, exclude_patterns=[], verbose=VERBOSE, fpath_list=None, reflags=0, cache=None): r""" greps for patterns Python implementation of grep. NOT FINISHED Args: regex_list (str or list): one or more patterns to find recursive (bool): dpath_list (list): directories to search (defaults to cwd) include_patterns (list) : defaults to standard file extensions Returns: (list, list, list): (found_fpaths, found_lines_list, found_lxs_list) CommandLine: python -m utool.util_path --test-grep utprof.py -m utool.util_path --exec-grep utprof.py utool/util_path.py --exec-grep Example: >>> # ENABLE_DOCTEST >>> from utool.util_path import * # NOQA >>> import utool as ut >>> #dpath_list = [ut.truepath('~/code/utool/utool')] >>> dpath_list = [ut.truepath(dirname(ut.__file__))] >>> include_patterns = ['*.py'] >>> exclude_dirs = [] >>> regex_list = ['grepfile'] >>> verbose = True >>> recursive = True >>> result = ut.grep(regex_list, recursive, dpath_list, include_patterns, >>> exclude_dirs) >>> (found_fpath_list, found_lines_list, found_lxs_list) = result >>> assert 'util_path.py' in list(map(basename, found_fpath_list)) """ from utool import util_regex # from utool import util_str from utool import util_list if include_patterns is None: include_patterns = ['*'] # include_patterns = get_standard_include_patterns() if greater_exclude_dirs is None: greater_exclude_dirs = [] # greater_exclude_dirs = get_standard_exclude_dnames() # ensure list input if isinstance(include_patterns, six.string_types): include_patterns = [include_patterns] if dpath_list is None: dpath_list = [os.getcwd()] if verbose: recursive_stat_str = ['flat', 'recursive'][recursive] print('[util_path] Greping (%s) %r for %r' % (recursive_stat_str, dpath_list, regex_list)) print('[util_path] regex_list = %s' % (regex_list)) if isinstance(regex_list, six.string_types): regex_list = [regex_list] found_fpath_list = [] found_lines_list = [] found_lxs_list = [] # Walk through each directory recursively if fpath_list is None: fpath_generator = matching_fpaths( dpath_list=dpath_list, include_patterns=include_patterns, exclude_dirs=exclude_dirs, greater_exclude_dirs=greater_exclude_dirs, exclude_patterns=exclude_patterns, recursive=recursive) else: fpath_generator = fpath_list # from utool import util_regex # extended_regex_list, reflags = util_regex.extend_regex3(regex_list, reflags) # if verbose: # print('extended_regex_list = %r' % (extended_regex_list,)) # print('reflags = %r' % (reflags,)) _exprs_flags = [util_regex.extend_regex2(expr, reflags) for expr in regex_list] extended_regex_list = util_list.take_column(_exprs_flags, 0) reflags_list = util_list.take_column(_exprs_flags, 1) # HACK reflags = reflags_list[0] # For each matching filepath for fpath in fpath_generator: # For each search pattern found_lines, found_lxs = grepfile(fpath, extended_regex_list, reflags_list, cache=cache) if inverse: if len(found_lines) == 0: # Append files that the pattern was not found in found_fpath_list.append(fpath) found_lines_list.append([]) found_lxs_list.append([]) elif len(found_lines) > 0: found_fpath_list.append(fpath) # regular matching found_lines_list.append(found_lines) found_lxs_list.append(found_lxs) grep_result = (found_fpath_list, found_lines_list, found_lxs_list) if verbose: print('==========') print('==========') print('[util_path] found matches in %d files' % len(found_fpath_list)) print(make_grep_resultstr(grep_result, extended_regex_list, reflags)) # print('[util_path] found matches in %d files' % len(found_fpath_list)) # pat = util_regex.regex_or(extended_regex_list) # for fpath, found, lxs in zip(found_fpath_list, found_lines_list, # found_lxs_list): # if len(found) > 0: # print('----------------------') # print('Found %d line(s) in %r: ' % (len(found), fpath)) # name = split(fpath)[1] # max_line = len(lxs) # ndigits = str(len(str(max_line))) # fmt_str = '%s : %' + ndigits + 'd |%s' # for (lx, line) in zip(lxs, found): # # hack # colored_line = util_str.highlight_regex( # line.rstrip('\n'), pat, reflags=reflags) # print(fmt_str % (name, lx, colored_line)) #print('[util_path] found matches in %d files' % len(found_fpath_list)) return grep_result
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 15; 2, function_name:find_lib_fpath; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 3, 12; 4, identifier:libname; 5, identifier:root_dir; 6, default_parameter; 6, 7; 6, 8; 7, identifier:recurse_down; 8, True; 9, default_parameter; 9, 10; 9, 11; 10, identifier:verbose; 11, False; 12, default_parameter; 12, 13; 12, 14; 13, identifier:debug; 14, False; 15, block; 15, 16; 15, 18; 15, 98; 15, 130; 15, 137; 15, 141; 15, 237; 15, 250; 15, 255; 15, 265; 16, expression_statement; 16, 17; 17, comment; 18, function_definition; 18, 19; 18, 20; 18, 22; 19, function_name:get_lib_fname_list; 20, parameters; 20, 21; 21, identifier:libname; 22, block; 22, 23; 22, 25; 22, 96; 23, expression_statement; 23, 24; 24, comment; 25, if_statement; 25, 26; 25, 34; 25, 47; 25, 66; 25, 85; 26, call; 26, 27; 26, 32; 27, attribute; 27, 28; 27, 31; 28, attribute; 28, 29; 28, 30; 29, identifier:sys; 30, identifier:platform; 31, identifier:startswith; 32, argument_list; 32, 33; 33, string:'win32'; 34, block; 34, 35; 35, expression_statement; 35, 36; 36, assignment; 36, 37; 36, 38; 37, identifier:libnames; 38, list:['lib' + libname + '.dll', libname + '.dll']; 38, 39; 38, 44; 39, binary_operator:+; 39, 40; 39, 43; 40, binary_operator:+; 40, 41; 40, 42; 41, string:'lib'; 42, identifier:libname; 43, string:'.dll'; 44, binary_operator:+; 44, 45; 44, 46; 45, identifier:libname; 46, string:'.dll'; 47, elif_clause; 47, 48; 47, 56; 48, call; 48, 49; 48, 54; 49, attribute; 49, 50; 49, 53; 50, attribute; 50, 51; 50, 52; 51, identifier:sys; 52, identifier:platform; 53, identifier:startswith; 54, argument_list; 54, 55; 55, string:'darwin'; 56, block; 56, 57; 57, expression_statement; 57, 58; 58, assignment; 58, 59; 58, 60; 59, identifier:libnames; 60, list:['lib' + libname + '.dylib']; 60, 61; 61, binary_operator:+; 61, 62; 61, 65; 62, binary_operator:+; 62, 63; 62, 64; 63, string:'lib'; 64, identifier:libname; 65, string:'.dylib'; 66, elif_clause; 66, 67; 66, 75; 67, call; 67, 68; 67, 73; 68, attribute; 68, 69; 68, 72; 69, attribute; 69, 70; 69, 71; 70, identifier:sys; 71, identifier:platform; 72, identifier:startswith; 73, argument_list; 73, 74; 74, string:'linux'; 75, block; 75, 76; 76, expression_statement; 76, 77; 77, assignment; 77, 78; 77, 79; 78, identifier:libnames; 79, list:['lib' + libname + '.so']; 79, 80; 80, binary_operator:+; 80, 81; 80, 84; 81, binary_operator:+; 81, 82; 81, 83; 82, string:'lib'; 83, identifier:libname; 84, string:'.so'; 85, else_clause; 85, 86; 86, block; 86, 87; 87, raise_statement; 87, 88; 88, call; 88, 89; 88, 90; 89, identifier:Exception; 90, argument_list; 90, 91; 91, binary_operator:%; 91, 92; 91, 93; 92, string:'Unknown operating system: %s'; 93, attribute; 93, 94; 93, 95; 94, identifier:sys; 95, identifier:platform; 96, return_statement; 96, 97; 97, identifier:libnames; 98, function_definition; 98, 99; 98, 100; 98, 102; 99, function_name:get_lib_dpath_list; 100, parameters; 100, 101; 101, identifier:root_dir; 102, block; 102, 103; 102, 105; 102, 107; 102, 128; 103, expression_statement; 103, 104; 104, comment; 105, expression_statement; 105, 106; 106, string:'returns possible lib locations'; 107, expression_statement; 107, 108; 108, assignment; 108, 109; 108, 110; 109, identifier:get_lib_dpath_list; 110, list:[root_dir, join(root_dir, 'lib'), join(root_dir, 'build'), join(root_dir, 'build', 'lib')]; 110, 111; 110, 112; 110, 117; 110, 122; 111, identifier:root_dir; 112, call; 112, 113; 112, 114; 113, identifier:join; 114, argument_list; 114, 115; 114, 116; 115, identifier:root_dir; 116, string:'lib'; 117, call; 117, 118; 117, 119; 118, identifier:join; 119, argument_list; 119, 120; 119, 121; 120, identifier:root_dir; 121, string:'build'; 122, call; 122, 123; 122, 124; 123, identifier:join; 124, argument_list; 124, 125; 124, 126; 124, 127; 125, identifier:root_dir; 126, string:'build'; 127, string:'lib'; 128, return_statement; 128, 129; 129, identifier:get_lib_dpath_list; 130, expression_statement; 130, 131; 131, assignment; 131, 132; 131, 133; 132, identifier:lib_fname_list; 133, call; 133, 134; 133, 135; 134, identifier:get_lib_fname_list; 135, argument_list; 135, 136; 136, identifier:libname; 137, expression_statement; 137, 138; 138, assignment; 138, 139; 138, 140; 139, identifier:tried_fpaths; 140, list:[]; 141, while_statement; 141, 142; 141, 145; 142, comparison_operator:is; 142, 143; 142, 144; 143, identifier:root_dir; 144, None; 145, block; 145, 146; 145, 232; 146, for_statement; 146, 147; 146, 148; 146, 149; 147, identifier:lib_fname; 148, identifier:lib_fname_list; 149, block; 149, 150; 149, 209; 149, 216; 150, for_statement; 150, 151; 150, 152; 150, 156; 151, identifier:lib_dpath; 152, call; 152, 153; 152, 154; 153, identifier:get_lib_dpath_list; 154, argument_list; 154, 155; 155, identifier:root_dir; 156, block; 156, 157; 156, 168; 157, expression_statement; 157, 158; 158, assignment; 158, 159; 158, 160; 159, identifier:lib_fpath; 160, call; 160, 161; 160, 162; 161, identifier:normpath; 162, argument_list; 162, 163; 163, call; 163, 164; 163, 165; 164, identifier:join; 165, argument_list; 165, 166; 165, 167; 166, identifier:lib_dpath; 167, identifier:lib_fname; 168, if_statement; 168, 169; 168, 173; 168, 199; 169, call; 169, 170; 169, 171; 170, identifier:exists; 171, argument_list; 171, 172; 172, identifier:lib_fpath; 173, block; 173, 174; 173, 187; 173, 197; 174, if_statement; 174, 175; 174, 176; 175, identifier:verbose; 176, block; 176, 177; 177, expression_statement; 177, 178; 178, call; 178, 179; 178, 180; 179, identifier:print; 180, argument_list; 180, 181; 181, call; 181, 182; 181, 185; 182, attribute; 182, 183; 182, 184; 183, string:'\n[c] Checked: '; 184, identifier:join; 185, argument_list; 185, 186; 186, identifier:tried_fpaths; 187, if_statement; 187, 188; 187, 189; 188, identifier:debug; 189, block; 189, 190; 190, expression_statement; 190, 191; 191, call; 191, 192; 191, 193; 192, identifier:print; 193, argument_list; 193, 194; 194, binary_operator:%; 194, 195; 194, 196; 195, string:'using: %r'; 196, identifier:lib_fpath; 197, return_statement; 197, 198; 198, identifier:lib_fpath; 199, else_clause; 199, 200; 199, 201; 200, comment; 201, block; 201, 202; 202, expression_statement; 202, 203; 203, call; 203, 204; 203, 207; 204, attribute; 204, 205; 204, 206; 205, identifier:tried_fpaths; 206, identifier:append; 207, argument_list; 207, 208; 208, identifier:lib_fpath; 209, expression_statement; 209, 210; 210, assignment; 210, 211; 210, 212; 211, identifier:_new_root; 212, call; 212, 213; 212, 214; 213, identifier:dirname; 214, argument_list; 214, 215; 215, identifier:root_dir; 216, if_statement; 216, 217; 216, 220; 216, 226; 217, comparison_operator:==; 217, 218; 217, 219; 218, identifier:_new_root; 219, identifier:root_dir; 220, block; 220, 221; 220, 225; 221, expression_statement; 221, 222; 222, assignment; 222, 223; 222, 224; 223, identifier:root_dir; 224, None; 225, break_statement; 226, else_clause; 226, 227; 227, block; 227, 228; 228, expression_statement; 228, 229; 229, assignment; 229, 230; 229, 231; 230, identifier:root_dir; 231, identifier:_new_root; 232, if_statement; 232, 233; 232, 235; 233, not_operator; 233, 234; 234, identifier:recurse_down; 235, block; 235, 236; 236, break_statement; 237, expression_statement; 237, 238; 238, assignment; 238, 239; 238, 240; 239, identifier:msg; 240, parenthesized_expression; 240, 241; 241, binary_operator:+; 241, 242; 241, 249; 242, binary_operator:%; 242, 243; 242, 244; 243, string:'\n[C!] load_clib(libname=%r root_dir=%r, recurse_down=%r, verbose=%r)'; 244, tuple; 244, 245; 244, 246; 244, 247; 244, 248; 245, identifier:libname; 246, identifier:root_dir; 247, identifier:recurse_down; 248, identifier:verbose; 249, string:'\n[c!] Cannot FIND dynamic library'; 250, expression_statement; 250, 251; 251, call; 251, 252; 251, 253; 252, identifier:print; 253, argument_list; 253, 254; 254, identifier:msg; 255, expression_statement; 255, 256; 256, call; 256, 257; 256, 258; 257, identifier:print; 258, argument_list; 258, 259; 259, call; 259, 260; 259, 263; 260, attribute; 260, 261; 260, 262; 261, string:'\n[c!] Checked: '; 262, identifier:join; 263, argument_list; 263, 264; 264, identifier:tried_fpaths; 265, raise_statement; 265, 266; 266, call; 266, 267; 266, 268; 267, identifier:ImportError; 268, argument_list; 268, 269; 269, identifier:msg
def find_lib_fpath(libname, root_dir, recurse_down=True, verbose=False, debug=False): """ Search for the library """ def get_lib_fname_list(libname): """ input <libname>: library name (e.g. 'hesaff', not 'libhesaff') returns <libnames>: list of plausible library file names """ if sys.platform.startswith('win32'): libnames = ['lib' + libname + '.dll', libname + '.dll'] elif sys.platform.startswith('darwin'): libnames = ['lib' + libname + '.dylib'] elif sys.platform.startswith('linux'): libnames = ['lib' + libname + '.so'] else: raise Exception('Unknown operating system: %s' % sys.platform) return libnames def get_lib_dpath_list(root_dir): """ input <root_dir>: deepest directory to look for a library (dll, so, dylib) returns <libnames>: list of plausible directories to look. """ 'returns possible lib locations' get_lib_dpath_list = [root_dir, join(root_dir, 'lib'), join(root_dir, 'build'), join(root_dir, 'build', 'lib')] return get_lib_dpath_list lib_fname_list = get_lib_fname_list(libname) tried_fpaths = [] while root_dir is not None: for lib_fname in lib_fname_list: for lib_dpath in get_lib_dpath_list(root_dir): lib_fpath = normpath(join(lib_dpath, lib_fname)) if exists(lib_fpath): if verbose: print('\n[c] Checked: '.join(tried_fpaths)) if debug: print('using: %r' % lib_fpath) return lib_fpath else: # Remember which candiate library fpaths did not exist tried_fpaths.append(lib_fpath) _new_root = dirname(root_dir) if _new_root == root_dir: root_dir = None break else: root_dir = _new_root if not recurse_down: break msg = ('\n[C!] load_clib(libname=%r root_dir=%r, recurse_down=%r, verbose=%r)' % (libname, root_dir, recurse_down, verbose) + '\n[c!] Cannot FIND dynamic library') print(msg) print('\n[c!] Checked: '.join(tried_fpaths)) raise ImportError(msg)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 17; 2, function_name:search_candidate_paths; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 3, 14; 4, identifier:candidate_path_list; 5, default_parameter; 5, 6; 5, 7; 6, identifier:candidate_name_list; 7, None; 8, default_parameter; 8, 9; 8, 10; 9, identifier:priority_paths; 10, None; 11, default_parameter; 11, 12; 11, 13; 12, identifier:required_subpaths; 13, list:[]; 14, default_parameter; 14, 15; 14, 16; 15, identifier:verbose; 16, None; 17, block; 17, 18; 17, 20; 17, 25; 17, 37; 17, 47; 17, 78; 17, 89; 17, 93; 17, 172; 17, 182; 18, expression_statement; 18, 19; 19, comment; 20, import_statement; 20, 21; 21, aliased_import; 21, 22; 21, 24; 22, dotted_name; 22, 23; 23, identifier:utool; 24, identifier:ut; 25, if_statement; 25, 26; 25, 29; 26, comparison_operator:is; 26, 27; 26, 28; 27, identifier:verbose; 28, None; 29, block; 29, 30; 30, expression_statement; 30, 31; 31, assignment; 31, 32; 31, 33; 32, identifier:verbose; 33, conditional_expression:if; 33, 34; 33, 35; 33, 36; 34, integer:0; 35, identifier:QUIET; 36, integer:1; 37, if_statement; 37, 38; 37, 41; 38, comparison_operator:>=; 38, 39; 38, 40; 39, identifier:verbose; 40, integer:1; 41, block; 41, 42; 42, expression_statement; 42, 43; 43, call; 43, 44; 43, 45; 44, identifier:print; 45, argument_list; 45, 46; 46, string:'[search_candidate_paths] Searching for candidate paths'; 47, if_statement; 47, 48; 47, 51; 47, 72; 48, comparison_operator:is; 48, 49; 48, 50; 49, identifier:candidate_name_list; 50, None; 51, block; 51, 52; 52, expression_statement; 52, 53; 53, assignment; 53, 54; 53, 55; 54, identifier:candidate_path_list_; 55, list_comprehension; 55, 56; 55, 61; 56, call; 56, 57; 56, 58; 57, identifier:join; 58, argument_list; 58, 59; 58, 60; 59, identifier:dpath; 60, identifier:fname; 61, for_in_clause; 61, 62; 61, 65; 62, pattern_list; 62, 63; 62, 64; 63, identifier:dpath; 64, identifier:fname; 65, call; 65, 66; 65, 69; 66, attribute; 66, 67; 66, 68; 67, identifier:itertools; 68, identifier:product; 69, argument_list; 69, 70; 69, 71; 70, identifier:candidate_path_list; 71, identifier:candidate_name_list; 72, else_clause; 72, 73; 73, block; 73, 74; 74, expression_statement; 74, 75; 75, assignment; 75, 76; 75, 77; 76, identifier:candidate_path_list_; 77, identifier:candidate_path_list; 78, if_statement; 78, 79; 78, 82; 79, comparison_operator:is; 79, 80; 79, 81; 80, identifier:priority_paths; 81, None; 82, block; 82, 83; 83, expression_statement; 83, 84; 84, assignment; 84, 85; 84, 86; 85, identifier:candidate_path_list_; 86, binary_operator:+; 86, 87; 86, 88; 87, identifier:priority_paths; 88, identifier:candidate_path_list_; 89, expression_statement; 89, 90; 90, assignment; 90, 91; 90, 92; 91, identifier:return_path; 92, None; 93, for_statement; 93, 94; 93, 95; 93, 96; 94, identifier:path; 95, identifier:candidate_path_list_; 96, block; 96, 97; 97, if_statement; 97, 98; 97, 106; 98, boolean_operator:and; 98, 99; 98, 102; 99, comparison_operator:is; 99, 100; 99, 101; 100, identifier:path; 101, None; 102, call; 102, 103; 102, 104; 103, identifier:exists; 104, argument_list; 104, 105; 105, identifier:path; 106, block; 106, 107; 106, 125; 106, 126; 106, 138; 107, if_statement; 107, 108; 107, 111; 108, comparison_operator:>=; 108, 109; 108, 110; 109, identifier:verbose; 110, integer:2; 111, block; 111, 112; 111, 120; 112, expression_statement; 112, 113; 113, call; 113, 114; 113, 115; 114, identifier:print; 115, argument_list; 115, 116; 116, binary_operator:%; 116, 117; 116, 118; 117, string:'[search_candidate_paths] Found candidate directory %r'; 118, tuple; 118, 119; 119, identifier:path; 120, expression_statement; 120, 121; 121, call; 121, 122; 121, 123; 122, identifier:print; 123, argument_list; 123, 124; 124, string:'[search_candidate_paths] ... checking for approprate structure'; 125, comment; 126, expression_statement; 126, 127; 127, assignment; 127, 128; 127, 129; 128, identifier:subpath_list; 129, list_comprehension; 129, 130; 129, 135; 130, call; 130, 131; 130, 132; 131, identifier:join; 132, argument_list; 132, 133; 132, 134; 133, identifier:path; 134, identifier:subpath; 135, for_in_clause; 135, 136; 135, 137; 136, identifier:subpath; 137, identifier:required_subpaths; 138, if_statement; 138, 139; 138, 154; 139, call; 139, 140; 139, 141; 140, identifier:all; 141, generator_expression; 141, 142; 141, 151; 142, call; 142, 143; 142, 146; 143, attribute; 143, 144; 143, 145; 144, identifier:ut; 145, identifier:checkpath; 146, argument_list; 146, 147; 146, 148; 147, identifier:path_; 148, keyword_argument; 148, 149; 148, 150; 149, identifier:verbose; 150, identifier:verbose; 151, for_in_clause; 151, 152; 151, 153; 152, identifier:path_; 153, identifier:subpath_list; 154, block; 154, 155; 154, 159; 154, 169; 154, 171; 155, expression_statement; 155, 156; 156, assignment; 156, 157; 156, 158; 157, identifier:return_path; 158, identifier:path; 159, if_statement; 159, 160; 159, 163; 160, comparison_operator:>=; 160, 161; 160, 162; 161, identifier:verbose; 162, integer:2; 163, block; 163, 164; 164, expression_statement; 164, 165; 165, call; 165, 166; 165, 167; 166, identifier:print; 167, argument_list; 167, 168; 168, string:'[search_candidate_paths] Found acceptable path'; 169, return_statement; 169, 170; 170, identifier:return_path; 171, break_statement; 172, if_statement; 172, 173; 172, 176; 173, comparison_operator:>=; 173, 174; 173, 175; 174, identifier:verbose; 175, integer:1; 176, block; 176, 177; 177, expression_statement; 177, 178; 178, call; 178, 179; 178, 180; 179, identifier:print; 180, argument_list; 180, 181; 181, string:'[search_candidate_paths] Failed to find acceptable path'; 182, return_statement; 182, 183; 183, identifier:return_path
def search_candidate_paths(candidate_path_list, candidate_name_list=None, priority_paths=None, required_subpaths=[], verbose=None): """ searches for existing paths that meed a requirement Args: candidate_path_list (list): list of paths to check. If candidate_name_list is specified this is the dpath list instead candidate_name_list (list): specifies several names to check (default = None) priority_paths (None): specifies paths to check first. Ignore candidate_name_list (default = None) required_subpaths (list): specified required directory structure (default = []) verbose (bool): verbosity flag(default = True) Returns: str: return_path CommandLine: python -m utool.util_path --test-search_candidate_paths Example: >>> # DISABLE_DOCTEST >>> from utool.util_path import * # NOQA >>> candidate_path_list = [ut.truepath('~/RPI/code/utool'), >>> ut.truepath('~/code/utool')] >>> candidate_name_list = None >>> required_subpaths = [] >>> verbose = True >>> priority_paths = None >>> return_path = search_candidate_paths(candidate_path_list, >>> candidate_name_list, >>> priority_paths, required_subpaths, >>> verbose) >>> result = ('return_path = %s' % (str(return_path),)) >>> print(result) """ import utool as ut if verbose is None: verbose = 0 if QUIET else 1 if verbose >= 1: print('[search_candidate_paths] Searching for candidate paths') if candidate_name_list is not None: candidate_path_list_ = [join(dpath, fname) for dpath, fname in itertools.product(candidate_path_list, candidate_name_list)] else: candidate_path_list_ = candidate_path_list if priority_paths is not None: candidate_path_list_ = priority_paths + candidate_path_list_ return_path = None for path in candidate_path_list_: if path is not None and exists(path): if verbose >= 2: print('[search_candidate_paths] Found candidate directory %r' % (path,)) print('[search_candidate_paths] ... checking for approprate structure') # tomcat directory exists. Make sure it also contains a webapps dir subpath_list = [join(path, subpath) for subpath in required_subpaths] if all(ut.checkpath(path_, verbose=verbose) for path_ in subpath_list): return_path = path if verbose >= 2: print('[search_candidate_paths] Found acceptable path') return return_path break if verbose >= 1: print('[search_candidate_paths] Failed to find acceptable path') return return_path
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 15; 2, function_name:symlink; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 3, 12; 4, identifier:real_path; 5, identifier:link_path; 6, default_parameter; 6, 7; 6, 8; 7, identifier:overwrite; 8, False; 9, default_parameter; 9, 10; 9, 11; 10, identifier:on_error; 11, string:'raise'; 12, default_parameter; 12, 13; 12, 14; 13, identifier:verbose; 14, integer:2; 15, block; 15, 16; 15, 18; 15, 25; 15, 32; 15, 46; 15, 134; 15, 215; 16, expression_statement; 16, 17; 17, comment; 18, expression_statement; 18, 19; 19, assignment; 19, 20; 19, 21; 20, identifier:path; 21, call; 21, 22; 21, 23; 22, identifier:normpath; 23, argument_list; 23, 24; 24, identifier:real_path; 25, expression_statement; 25, 26; 26, assignment; 26, 27; 26, 28; 27, identifier:link; 28, call; 28, 29; 28, 30; 29, identifier:normpath; 30, argument_list; 30, 31; 31, identifier:link_path; 32, if_statement; 32, 33; 32, 34; 33, identifier:verbose; 34, block; 34, 35; 35, expression_statement; 35, 36; 36, call; 36, 37; 36, 38; 37, identifier:print; 38, argument_list; 38, 39; 39, call; 39, 40; 39, 43; 40, attribute; 40, 41; 40, 42; 41, string:'[util_path] Creating symlink: path={} link={}'; 42, identifier:format; 43, argument_list; 43, 44; 43, 45; 44, identifier:path; 45, identifier:link; 46, if_statement; 46, 47; 46, 55; 47, call; 47, 48; 47, 53; 48, attribute; 48, 49; 48, 52; 49, attribute; 49, 50; 49, 51; 50, identifier:os; 51, identifier:path; 52, identifier:islink; 53, argument_list; 53, 54; 54, identifier:link; 55, block; 55, 56; 55, 64; 55, 73; 55, 106; 55, 116; 56, if_statement; 56, 57; 56, 58; 57, identifier:verbose; 58, block; 58, 59; 59, expression_statement; 59, 60; 60, call; 60, 61; 60, 62; 61, identifier:print; 62, argument_list; 62, 63; 63, string:'[util_path] symlink already exists'; 64, expression_statement; 64, 65; 65, assignment; 65, 66; 65, 67; 66, identifier:os_readlink; 67, call; 67, 68; 67, 69; 68, identifier:getattr; 69, argument_list; 69, 70; 69, 71; 69, 72; 70, identifier:os; 71, string:"readlink"; 72, None; 73, if_statement; 73, 74; 73, 78; 73, 99; 74, call; 74, 75; 74, 76; 75, identifier:callable; 76, argument_list; 76, 77; 77, identifier:os_readlink; 78, block; 78, 79; 79, if_statement; 79, 80; 79, 86; 80, comparison_operator:==; 80, 81; 80, 85; 81, call; 81, 82; 81, 83; 82, identifier:os_readlink; 83, argument_list; 83, 84; 84, identifier:link; 85, identifier:path; 86, block; 86, 87; 86, 97; 87, if_statement; 87, 88; 87, 91; 88, comparison_operator:>; 88, 89; 88, 90; 89, identifier:verbose; 90, integer:1; 91, block; 91, 92; 92, expression_statement; 92, 93; 93, call; 93, 94; 93, 95; 94, identifier:print; 95, argument_list; 95, 96; 96, string:'[path] ... and points to the right place'; 97, return_statement; 97, 98; 98, identifier:link; 99, else_clause; 99, 100; 100, block; 100, 101; 101, expression_statement; 101, 102; 102, call; 102, 103; 102, 104; 103, identifier:print; 104, argument_list; 104, 105; 105, string:'[util_path] Warning, symlinks are not implemented on windows'; 106, if_statement; 106, 107; 106, 110; 107, comparison_operator:>; 107, 108; 107, 109; 108, identifier:verbose; 109, integer:1; 110, block; 110, 111; 111, expression_statement; 111, 112; 112, call; 112, 113; 112, 114; 113, identifier:print; 114, argument_list; 114, 115; 115, string:'[util_path] ... but it points somewhere else'; 116, if_statement; 116, 117; 116, 118; 116, 127; 117, identifier:overwrite; 118, block; 118, 119; 119, expression_statement; 119, 120; 120, call; 120, 121; 120, 122; 121, identifier:delete; 122, argument_list; 122, 123; 122, 124; 123, identifier:link; 124, comparison_operator:>; 124, 125; 124, 126; 125, identifier:verbose; 126, integer:1; 127, elif_clause; 127, 128; 127, 131; 128, comparison_operator:==; 128, 129; 128, 130; 129, identifier:on_error; 130, string:'ignore'; 131, block; 131, 132; 132, return_statement; 132, 133; 133, False; 134, try_statement; 134, 135; 134, 165; 135, block; 135, 136; 135, 145; 136, expression_statement; 136, 137; 137, assignment; 137, 138; 137, 139; 138, identifier:os_symlink; 139, call; 139, 140; 139, 141; 140, identifier:getattr; 141, argument_list; 141, 142; 141, 143; 141, 144; 142, identifier:os; 143, string:"symlink"; 144, None; 145, if_statement; 145, 146; 145, 150; 145, 157; 146, call; 146, 147; 146, 148; 147, identifier:callable; 148, argument_list; 148, 149; 149, identifier:os_symlink; 150, block; 150, 151; 151, expression_statement; 151, 152; 152, call; 152, 153; 152, 154; 153, identifier:os_symlink; 154, argument_list; 154, 155; 154, 156; 155, identifier:path; 156, identifier:link; 157, else_clause; 157, 158; 158, block; 158, 159; 159, expression_statement; 159, 160; 160, call; 160, 161; 160, 162; 161, identifier:win_shortcut; 162, argument_list; 162, 163; 162, 164; 163, identifier:path; 164, identifier:link; 165, except_clause; 165, 166; 165, 170; 166, as_pattern; 166, 167; 166, 168; 167, identifier:Exception; 168, as_pattern_target; 168, 169; 169, identifier:ex; 170, block; 170, 171; 170, 176; 170, 184; 170, 192; 170, 199; 170, 211; 171, import_statement; 171, 172; 172, aliased_import; 172, 173; 172, 175; 173, dotted_name; 173, 174; 174, identifier:utool; 175, identifier:ut; 176, expression_statement; 176, 177; 177, call; 177, 178; 177, 179; 178, identifier:checkpath; 179, argument_list; 179, 180; 179, 181; 180, identifier:link; 181, keyword_argument; 181, 182; 181, 183; 182, identifier:verbose; 183, True; 184, expression_statement; 184, 185; 185, call; 185, 186; 185, 187; 186, identifier:checkpath; 187, argument_list; 187, 188; 187, 189; 188, identifier:path; 189, keyword_argument; 189, 190; 189, 191; 190, identifier:verbose; 191, True; 192, expression_statement; 192, 193; 193, assignment; 193, 194; 193, 195; 194, identifier:do_raise; 195, parenthesized_expression; 195, 196; 196, comparison_operator:==; 196, 197; 196, 198; 197, identifier:on_error; 198, string:'raise'; 199, expression_statement; 199, 200; 200, call; 200, 201; 200, 204; 201, attribute; 201, 202; 201, 203; 202, identifier:ut; 203, identifier:printex; 204, argument_list; 204, 205; 204, 206; 204, 207; 205, identifier:ex; 206, string:'[util_path] error making symlink'; 207, keyword_argument; 207, 208; 207, 209; 208, identifier:iswarning; 209, not_operator; 209, 210; 210, identifier:do_raise; 211, if_statement; 211, 212; 211, 213; 212, identifier:do_raise; 213, block; 213, 214; 214, raise_statement; 215, return_statement; 215, 216; 216, identifier:link
def symlink(real_path, link_path, overwrite=False, on_error='raise', verbose=2): """ Attempt to create a symbolic link. TODO: Can this be fixed on windows? Args: path (str): path to real file or directory link_path (str): path to desired location for symlink overwrite (bool): overwrite existing symlinks (default = False) on_error (str): strategy for dealing with errors. raise or ignore verbose (int): verbosity level (default=2) Returns: str: link path CommandLine: python -m utool.util_path symlink Example: >>> # ENABLE_DOCTEST >>> from utool.util_path import * # NOQA >>> import utool as ut >>> dpath = ut.get_app_resource_dir('utool') >>> real_path = join(dpath, 'real_file.txt') >>> link_path = join(dpath, 'link_file.txt') >>> ut.emap(ut.delete, [real_path, link_path], verbose=0) >>> ut.writeto(real_path, 'foo') >>> result = symlink(real_path, link_path) >>> assert ut.readfrom(result) == 'foo' >>> ut.emap(ut.delete, [real_path, link_path], verbose=0) Example: >>> # ENABLE_DOCTEST >>> from utool.util_path import * # NOQA >>> import utool as ut >>> real_dpath = ut.get_app_resource_dir('utool', 'real_dpath') >>> link_dpath = ut.augpath(real_dpath, newfname='link_dpath') >>> real_path = join(real_dpath, 'afile.txt') >>> link_path = join(link_dpath, 'afile.txt') >>> ut.emap(ut.delete, [real_path, link_path], verbose=0) >>> ut.ensuredir(real_dpath) >>> ut.writeto(real_path, 'foo') >>> result = symlink(real_dpath, link_dpath) >>> assert ut.readfrom(link_path) == 'foo' >>> ut.delete(link_dpath, verbose=0) >>> assert ut.checkpath(real_path) >>> ut.delete(real_dpath, verbose=0) >>> assert not ut.checkpath(real_path) """ path = normpath(real_path) link = normpath(link_path) if verbose: print('[util_path] Creating symlink: path={} link={}'.format(path, link)) if os.path.islink(link): if verbose: print('[util_path] symlink already exists') os_readlink = getattr(os, "readlink", None) if callable(os_readlink): if os_readlink(link) == path: if verbose > 1: print('[path] ... and points to the right place') return link else: print('[util_path] Warning, symlinks are not implemented on windows') if verbose > 1: print('[util_path] ... but it points somewhere else') if overwrite: delete(link, verbose > 1) elif on_error == 'ignore': return False try: os_symlink = getattr(os, "symlink", None) if callable(os_symlink): os_symlink(path, link) else: win_shortcut(path, link) except Exception as ex: import utool as ut checkpath(link, verbose=True) checkpath(path, verbose=True) do_raise = (on_error == 'raise') ut.printex(ex, '[util_path] error making symlink', iswarning=not do_raise) if do_raise: raise return link
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 13; 2, function_name:view_directory; 3, parameters; 3, 4; 3, 7; 3, 10; 4, default_parameter; 4, 5; 4, 6; 5, identifier:dname; 6, None; 7, default_parameter; 7, 8; 7, 9; 8, identifier:fname; 9, None; 10, default_parameter; 10, 11; 10, 12; 11, identifier:verbose; 12, True; 13, block; 13, 14; 13, 16; 13, 22; 13, 28; 13, 29; 13, 47; 13, 57; 13, 70; 13, 85; 13, 92; 13, 104; 13, 127; 13, 128; 13, 129; 13, 130; 13, 131; 13, 132; 13, 133; 13, 134; 13, 135; 13, 136; 13, 137; 13, 143; 13, 153; 14, expression_statement; 14, 15; 15, comment; 16, import_from_statement; 16, 17; 16, 20; 17, dotted_name; 17, 18; 17, 19; 18, identifier:utool; 19, identifier:util_arg; 20, dotted_name; 20, 21; 21, identifier:STRICT; 22, import_from_statement; 22, 23; 22, 26; 23, dotted_name; 23, 24; 23, 25; 24, identifier:utool; 25, identifier:util_path; 26, dotted_name; 26, 27; 27, identifier:checkpath; 28, comment; 29, if_statement; 29, 30; 29, 39; 30, boolean_operator:and; 30, 31; 30, 32; 31, identifier:HAVE_PATHLIB; 32, call; 32, 33; 32, 34; 33, identifier:isinstance; 34, argument_list; 34, 35; 34, 36; 35, identifier:dname; 36, attribute; 36, 37; 36, 38; 37, identifier:pathlib; 38, identifier:Path; 39, block; 39, 40; 40, expression_statement; 40, 41; 41, assignment; 41, 42; 41, 43; 42, identifier:dname; 43, call; 43, 44; 43, 45; 44, identifier:str; 45, argument_list; 45, 46; 46, identifier:dname; 47, if_statement; 47, 48; 47, 49; 48, identifier:verbose; 49, block; 49, 50; 50, expression_statement; 50, 51; 51, call; 51, 52; 51, 53; 52, identifier:print; 53, argument_list; 53, 54; 54, binary_operator:%; 54, 55; 54, 56; 55, string:'[cplat] view_directory(%r) '; 56, identifier:dname; 57, expression_statement; 57, 58; 58, assignment; 58, 59; 58, 60; 59, identifier:dname; 60, conditional_expression:if; 60, 61; 60, 66; 60, 69; 61, call; 61, 62; 61, 65; 62, attribute; 62, 63; 62, 64; 63, identifier:os; 64, identifier:getcwd; 65, argument_list; 66, comparison_operator:is; 66, 67; 66, 68; 67, identifier:dname; 68, None; 69, identifier:dname; 70, expression_statement; 70, 71; 71, assignment; 71, 72; 71, 73; 72, identifier:open_prog; 73, subscript; 73, 74; 73, 84; 74, dictionary; 74, 75; 74, 78; 74, 81; 75, pair; 75, 76; 75, 77; 76, string:'win32'; 77, string:'explorer.exe'; 78, pair; 78, 79; 78, 80; 79, string:'linux'; 80, string:'nautilus'; 81, pair; 81, 82; 81, 83; 82, string:'darwin'; 83, string:'open'; 84, identifier:OS_TYPE; 85, expression_statement; 85, 86; 86, assignment; 86, 87; 86, 88; 87, identifier:dname; 88, call; 88, 89; 88, 90; 89, identifier:normpath; 90, argument_list; 90, 91; 91, identifier:dname; 92, if_statement; 92, 93; 92, 94; 93, identifier:STRICT; 94, block; 94, 95; 95, assert_statement; 95, 96; 95, 103; 96, call; 96, 97; 96, 98; 97, identifier:checkpath; 98, argument_list; 98, 99; 98, 100; 99, identifier:dname; 100, keyword_argument; 100, 101; 100, 102; 101, identifier:verbose; 102, identifier:verbose; 103, string:'directory doesnt exit'; 104, if_statement; 104, 105; 104, 112; 104, 121; 105, boolean_operator:and; 105, 106; 105, 109; 106, comparison_operator:is; 106, 107; 106, 108; 107, identifier:fname; 108, None; 109, comparison_operator:==; 109, 110; 109, 111; 110, identifier:OS_TYPE; 111, string:'linux'; 112, block; 112, 113; 113, expression_statement; 113, 114; 114, assignment; 114, 115; 114, 116; 115, identifier:arg; 116, call; 116, 117; 116, 118; 117, identifier:join; 118, argument_list; 118, 119; 118, 120; 119, identifier:dname; 120, identifier:fname; 121, else_clause; 121, 122; 122, block; 122, 123; 123, expression_statement; 123, 124; 124, assignment; 124, 125; 124, 126; 125, identifier:arg; 126, identifier:dname; 127, comment; 128, comment; 129, comment; 130, comment; 131, comment; 132, comment; 133, comment; 134, comment; 135, comment; 136, comment; 137, expression_statement; 137, 138; 138, assignment; 138, 139; 138, 140; 139, identifier:args; 140, tuple; 140, 141; 140, 142; 141, identifier:open_prog; 142, identifier:arg; 143, expression_statement; 143, 144; 144, call; 144, 145; 144, 146; 145, identifier:print; 146, argument_list; 146, 147; 147, call; 147, 148; 147, 151; 148, attribute; 148, 149; 148, 150; 149, identifier:subprocess; 150, identifier:list2cmdline; 151, argument_list; 151, 152; 152, identifier:args; 153, expression_statement; 153, 154; 154, call; 154, 155; 154, 158; 155, attribute; 155, 156; 155, 157; 156, identifier:subprocess; 157, identifier:Popen; 158, argument_list; 158, 159; 159, identifier:args
def view_directory(dname=None, fname=None, verbose=True): """ View a directory in the operating system file browser. Currently supports windows explorer, mac open, and linux nautlius. Args: dname (str): directory name fname (str): a filename to select in the directory (nautlius only) verbose (bool): CommandLine: python -m utool.util_cplat --test-view_directory Example: >>> # DISABLE_DOCTEST >>> # DOCTEST_DISABLE >>> from utool.util_cplat import * # NOQA >>> import utool as ut >>> dname = ut.truepath('~') >>> verbose = True >>> view_directory(dname, verbose) Example: >>> # DISABLE_DOCTEST >>> from utool.util_cplat import * # NOQA >>> import utool as ut >>> base = ut.ensure_app_cache_dir('utool', 'test_vd') >>> dirs = [ >>> '', >>> 'dir1', >>> 'has space', >>> 'space at end ', >>> ' space at start ', >>> '"quotes and spaces"', >>> "'single quotes and spaces'", >>> 'Frogram Piles (y2K)', >>> ] >>> dirs_ = [ut.ensuredir(join(base, d)) for d in dirs] >>> for dname in dirs_: >>> ut.view_directory(dname, verbose=False) >>> fpath = join(base, 'afile.txt') >>> ut.touch(fpath) >>> ut.view_directory(base, fpath, verbose=False) """ from utool.util_arg import STRICT from utool.util_path import checkpath # from utool.util_str import SINGLE_QUOTE, DOUBLE_QUOTE if HAVE_PATHLIB and isinstance(dname, pathlib.Path): dname = str(dname) if verbose: print('[cplat] view_directory(%r) ' % dname) dname = os.getcwd() if dname is None else dname open_prog = { 'win32': 'explorer.exe', 'linux': 'nautilus', 'darwin': 'open' }[OS_TYPE] dname = normpath(dname) if STRICT: assert checkpath(dname, verbose=verbose), 'directory doesnt exit' if fname is not None and OS_TYPE == 'linux': arg = join(dname, fname) else: arg = dname # if ' ' in dname and not dname.startswith((SINGLE_QUOTE, DOUBLE_QUOTE)): # # Ensure quotations # dname = '"%s"' % dname # if not WIN32: # arg = dname # # arg = subprocess.list2cmdline([dname]) # # arg = pipes.quote(dname) # else: # arg = dname # spawn and detatch process args = (open_prog, arg) print(subprocess.list2cmdline(args)) subprocess.Popen(args)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 7; 2, function_name:__parse_cmd_args; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:args; 5, identifier:sudo; 6, identifier:shell; 7, block; 7, 8; 7, 10; 7, 11; 7, 39; 7, 234; 7, 276; 7, 277; 7, 278; 7, 279; 7, 280; 7, 281; 7, 317; 8, expression_statement; 8, 9; 9, comment; 10, comment; 11, if_statement; 11, 12; 11, 32; 12, boolean_operator:and; 12, 13; 12, 25; 13, boolean_operator:and; 13, 14; 13, 19; 14, call; 14, 15; 14, 16; 15, identifier:isinstance; 16, argument_list; 16, 17; 16, 18; 17, identifier:args; 18, identifier:tuple; 19, comparison_operator:==; 19, 20; 19, 24; 20, call; 20, 21; 20, 22; 21, identifier:len; 22, argument_list; 22, 23; 23, identifier:args; 24, integer:1; 25, call; 25, 26; 25, 27; 26, identifier:isinstance; 27, argument_list; 27, 28; 27, 31; 28, subscript; 28, 29; 28, 30; 29, identifier:args; 30, integer:0; 31, identifier:tuple; 32, block; 32, 33; 33, expression_statement; 33, 34; 34, assignment; 34, 35; 34, 36; 35, identifier:args; 36, subscript; 36, 37; 36, 38; 37, identifier:args; 38, integer:0; 39, if_statement; 39, 40; 39, 41; 39, 42; 39, 131; 40, identifier:shell; 41, comment; 42, block; 42, 43; 43, if_statement; 43, 44; 43, 51; 43, 53; 43, 78; 44, call; 44, 45; 44, 46; 45, identifier:isinstance; 46, argument_list; 46, 47; 46, 48; 47, identifier:args; 48, attribute; 48, 49; 48, 50; 49, identifier:six; 50, identifier:string_types; 51, block; 51, 52; 52, pass_statement; 53, elif_clause; 53, 54; 53, 68; 54, boolean_operator:and; 54, 55; 54, 62; 55, call; 55, 56; 55, 57; 56, identifier:isinstance; 57, argument_list; 57, 58; 57, 59; 58, identifier:args; 59, tuple; 59, 60; 59, 61; 60, identifier:list; 61, identifier:tuple; 62, comparison_operator:>; 62, 63; 62, 67; 63, call; 63, 64; 63, 65; 64, identifier:len; 65, argument_list; 65, 66; 66, identifier:args; 67, integer:1; 68, block; 68, 69; 69, expression_statement; 69, 70; 70, assignment; 70, 71; 70, 72; 71, identifier:args; 72, call; 72, 73; 72, 76; 73, attribute; 73, 74; 73, 75; 74, string:' '; 75, identifier:join; 76, argument_list; 76, 77; 77, identifier:args; 78, elif_clause; 78, 79; 78, 93; 79, boolean_operator:and; 79, 80; 79, 87; 80, call; 80, 81; 80, 82; 81, identifier:isinstance; 82, argument_list; 82, 83; 82, 84; 83, identifier:args; 84, tuple; 84, 85; 84, 86; 85, identifier:list; 86, identifier:tuple; 87, comparison_operator:==; 87, 88; 87, 92; 88, call; 88, 89; 88, 90; 89, identifier:len; 90, argument_list; 90, 91; 91, identifier:args; 92, integer:1; 93, block; 93, 94; 94, if_statement; 94, 95; 94, 104; 94, 114; 95, call; 95, 96; 95, 97; 96, identifier:isinstance; 97, argument_list; 97, 98; 97, 101; 98, subscript; 98, 99; 98, 100; 99, identifier:args; 100, integer:0; 101, tuple; 101, 102; 101, 103; 102, identifier:tuple; 103, identifier:list; 104, block; 104, 105; 105, expression_statement; 105, 106; 106, assignment; 106, 107; 106, 108; 107, identifier:args; 108, call; 108, 109; 108, 112; 109, attribute; 109, 110; 109, 111; 110, string:' '; 111, identifier:join; 112, argument_list; 112, 113; 113, identifier:args; 114, elif_clause; 114, 115; 114, 124; 115, call; 115, 116; 115, 117; 116, identifier:isinstance; 117, argument_list; 117, 118; 117, 121; 118, subscript; 118, 119; 118, 120; 119, identifier:args; 120, integer:0; 121, attribute; 121, 122; 121, 123; 122, identifier:six; 123, identifier:string_types; 124, block; 124, 125; 125, expression_statement; 125, 126; 126, assignment; 126, 127; 126, 128; 127, identifier:args; 128, subscript; 128, 129; 128, 130; 129, identifier:args; 130, integer:0; 131, else_clause; 131, 132; 131, 133; 132, comment; 133, block; 133, 134; 134, if_statement; 134, 135; 134, 142; 134, 156; 135, call; 135, 136; 135, 137; 136, identifier:isinstance; 137, argument_list; 137, 138; 137, 139; 138, identifier:args; 139, attribute; 139, 140; 139, 141; 140, identifier:six; 141, identifier:string_types; 142, block; 142, 143; 143, expression_statement; 143, 144; 144, assignment; 144, 145; 144, 146; 145, identifier:args; 146, call; 146, 147; 146, 150; 147, attribute; 147, 148; 147, 149; 148, identifier:shlex; 149, identifier:split; 150, argument_list; 150, 151; 150, 152; 151, identifier:args; 152, keyword_argument; 152, 153; 152, 154; 153, identifier:posix; 154, not_operator; 154, 155; 155, identifier:WIN32; 156, elif_clause; 156, 157; 156, 164; 157, call; 157, 158; 157, 159; 158, identifier:isinstance; 159, argument_list; 159, 160; 159, 161; 160, identifier:args; 161, tuple; 161, 162; 161, 163; 162, identifier:list; 163, identifier:tuple; 164, block; 164, 165; 165, if_statement; 165, 166; 165, 172; 165, 180; 166, comparison_operator:>; 166, 167; 166, 171; 167, call; 167, 168; 167, 169; 168, identifier:len; 169, argument_list; 169, 170; 170, identifier:args; 171, integer:1; 172, block; 172, 173; 173, expression_statement; 173, 174; 174, assignment; 174, 175; 174, 176; 175, identifier:args; 176, call; 176, 177; 176, 178; 177, identifier:tuple; 178, argument_list; 178, 179; 179, identifier:args; 180, elif_clause; 180, 181; 180, 187; 181, comparison_operator:==; 181, 182; 181, 186; 182, call; 182, 183; 182, 184; 183, identifier:len; 184, argument_list; 184, 185; 185, identifier:args; 186, integer:1; 187, block; 187, 188; 188, if_statement; 188, 189; 188, 198; 188, 208; 189, call; 189, 190; 189, 191; 190, identifier:isinstance; 191, argument_list; 191, 192; 191, 195; 192, subscript; 192, 193; 192, 194; 193, identifier:args; 194, integer:0; 195, tuple; 195, 196; 195, 197; 196, identifier:tuple; 197, identifier:list; 198, block; 198, 199; 199, expression_statement; 199, 200; 200, assignment; 200, 201; 200, 202; 201, identifier:args; 202, call; 202, 203; 202, 204; 203, identifier:tuple; 204, argument_list; 204, 205; 205, subscript; 205, 206; 205, 207; 206, identifier:args; 207, integer:0; 208, elif_clause; 208, 209; 208, 218; 209, call; 209, 210; 209, 211; 210, identifier:isinstance; 211, argument_list; 211, 212; 211, 215; 212, subscript; 212, 213; 212, 214; 213, identifier:args; 214, integer:0; 215, attribute; 215, 216; 215, 217; 216, identifier:six; 217, identifier:string_types; 218, block; 218, 219; 219, expression_statement; 219, 220; 220, assignment; 220, 221; 220, 222; 221, identifier:args; 222, call; 222, 223; 222, 226; 223, attribute; 223, 224; 223, 225; 224, identifier:shlex; 225, identifier:split; 226, argument_list; 226, 227; 226, 230; 227, subscript; 227, 228; 227, 229; 228, identifier:args; 229, integer:0; 230, keyword_argument; 230, 231; 230, 232; 231, identifier:posix; 232, not_operator; 232, 233; 233, identifier:WIN32; 234, if_statement; 234, 235; 234, 238; 235, comparison_operator:is; 235, 236; 235, 237; 236, identifier:sudo; 237, True; 238, block; 238, 239; 239, if_statement; 239, 240; 239, 242; 239, 272; 240, not_operator; 240, 241; 241, identifier:WIN32; 242, block; 242, 243; 242, 267; 242, 268; 242, 269; 242, 270; 242, 271; 243, if_statement; 243, 244; 243, 245; 243, 252; 244, identifier:shell; 245, block; 245, 246; 246, expression_statement; 246, 247; 247, assignment; 247, 248; 247, 249; 248, identifier:args; 249, binary_operator:+; 249, 250; 249, 251; 250, string:'sudo '; 251, identifier:args; 252, else_clause; 252, 253; 253, block; 253, 254; 254, expression_statement; 254, 255; 255, assignment; 255, 256; 255, 257; 256, identifier:args; 257, binary_operator:+; 257, 258; 257, 263; 258, call; 258, 259; 258, 260; 259, identifier:tuple; 260, argument_list; 260, 261; 261, list:['sudo']; 261, 262; 262, string:'sudo'; 263, call; 263, 264; 263, 265; 264, identifier:tuple; 265, argument_list; 265, 266; 266, identifier:args; 267, comment; 268, comment; 269, comment; 270, comment; 271, comment; 272, else_clause; 272, 273; 272, 274; 273, comment; 274, block; 274, 275; 275, pass_statement; 276, comment; 277, comment; 278, comment; 279, comment; 280, comment; 281, if_statement; 281, 282; 281, 283; 282, identifier:WIN32; 283, block; 283, 284; 284, if_statement; 284, 285; 284, 301; 285, boolean_operator:and; 285, 286; 285, 292; 286, comparison_operator:==; 286, 287; 286, 291; 287, call; 287, 288; 287, 289; 288, identifier:len; 289, argument_list; 289, 290; 290, identifier:args; 291, integer:1; 292, call; 292, 293; 292, 294; 293, identifier:isinstance; 294, argument_list; 294, 295; 294, 298; 295, subscript; 295, 296; 295, 297; 296, identifier:args; 297, integer:0; 298, attribute; 298, 299; 298, 300; 299, identifier:six; 300, identifier:string_types; 301, block; 301, 302; 302, expression_statement; 302, 303; 303, assignment; 303, 304; 303, 305; 304, identifier:args; 305, call; 305, 306; 305, 309; 306, attribute; 306, 307; 306, 308; 307, identifier:shlex; 308, identifier:split; 309, argument_list; 309, 310; 309, 313; 310, subscript; 310, 311; 310, 312; 311, identifier:args; 312, integer:0; 313, keyword_argument; 313, 314; 313, 315; 314, identifier:posix; 315, not_operator; 315, 316; 316, identifier:WIN32; 317, return_statement; 317, 318; 318, identifier:args
def __parse_cmd_args(args, sudo, shell): """ When shell is True, Popen will only accept strings. No tuples Shell really should not be true. Returns: args suitable for subprocess.Popen I'm not quite sure what those are yet. Plain old string seem to work well? But I remember needing shlex at some point. CommandLine: python -m utool.util_cplat --test-__parse_cmd_args Example: >>> # DISABLE_DOCTEST >>> from utool.util_cplat import * # NOQA >>> # build test data >>> args = 'echo "hello world"' >>> sudo = False >>> shell = False >>> # execute function >>> args = __parse_cmd_args(args, sudo, shell) >>> # verify results >>> result = str(args) >>> print(result) """ # Case where tuple is passed in as only argument if isinstance(args, tuple) and len(args) == 1 and isinstance(args[0], tuple): args = args[0] if shell: # When shell is True, ensure args is a string if isinstance(args, six.string_types): pass elif isinstance(args, (list, tuple)) and len(args) > 1: args = ' '.join(args) elif isinstance(args, (list, tuple)) and len(args) == 1: if isinstance(args[0], (tuple, list)): args = ' '.join(args) elif isinstance(args[0], six.string_types): args = args[0] else: # When shell is False, ensure args is a tuple if isinstance(args, six.string_types): args = shlex.split(args, posix=not WIN32) elif isinstance(args, (list, tuple)): if len(args) > 1: args = tuple(args) elif len(args) == 1: if isinstance(args[0], (tuple, list)): args = tuple(args[0]) elif isinstance(args[0], six.string_types): args = shlex.split(args[0], posix=not WIN32) if sudo is True: if not WIN32: if shell: args = 'sudo ' + args else: args = tuple(['sudo']) + tuple(args) #if isinstance(args, six.string_types): # args = shlex.split(args) #args = ['sudo'] + args ## using sudo means we need to use a single string I believe #args = ' '.join(args) else: # TODO: strip out sudos pass # HACK FOR WINDOWS AGAIN # makes this command work: # python -c "import utool as ut; ut.cmd('build\\hesaffexe.exe ' + ut.grab_test_imgpath('star.png'))" # and this should still work # python -c "import utool as ut; ut.cmd('build\\hesaffexe.exe', ut.grab_test_imgpath('star.png'))" if WIN32: if len(args) == 1 and isinstance(args[0], six.string_types): args = shlex.split(args[0], posix=not WIN32) return args
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 17; 2, function_name:cmd2; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 3, 14; 4, identifier:command; 5, default_parameter; 5, 6; 5, 7; 6, identifier:shell; 7, False; 8, default_parameter; 8, 9; 8, 10; 9, identifier:detatch; 10, False; 11, default_parameter; 11, 12; 11, 13; 12, identifier:verbose; 13, False; 14, default_parameter; 14, 15; 14, 16; 15, identifier:verbout; 16, None; 17, block; 17, 18; 17, 20; 17, 23; 17, 37; 17, 50; 17, 59; 17, 70; 17, 103; 17, 128; 17, 283; 17, 293; 18, expression_statement; 18, 19; 19, comment; 20, import_statement; 20, 21; 21, dotted_name; 21, 22; 22, identifier:shlex; 23, if_statement; 23, 24; 23, 31; 24, call; 24, 25; 24, 26; 25, identifier:isinstance; 26, argument_list; 26, 27; 26, 28; 27, identifier:command; 28, tuple; 28, 29; 28, 30; 29, identifier:list; 30, identifier:tuple; 31, block; 31, 32; 32, raise_statement; 32, 33; 33, call; 33, 34; 33, 35; 34, identifier:ValueError; 35, argument_list; 35, 36; 36, string:'command tuple not supported yet'; 37, expression_statement; 37, 38; 38, assignment; 38, 39; 38, 40; 39, identifier:args; 40, call; 40, 41; 40, 44; 41, attribute; 41, 42; 41, 43; 42, identifier:shlex; 43, identifier:split; 44, argument_list; 44, 45; 44, 46; 45, identifier:command; 46, keyword_argument; 46, 47; 46, 48; 47, identifier:posix; 48, not_operator; 48, 49; 49, identifier:WIN32; 50, if_statement; 50, 51; 50, 54; 51, comparison_operator:is; 51, 52; 51, 53; 52, identifier:verbose; 53, True; 54, block; 54, 55; 55, expression_statement; 55, 56; 56, assignment; 56, 57; 56, 58; 57, identifier:verbose; 58, integer:2; 59, if_statement; 59, 60; 59, 63; 60, comparison_operator:is; 60, 61; 60, 62; 61, identifier:verbout; 62, None; 63, block; 63, 64; 64, expression_statement; 64, 65; 65, assignment; 65, 66; 65, 67; 66, identifier:verbout; 67, comparison_operator:>=; 67, 68; 67, 69; 68, identifier:verbose; 69, integer:1; 70, if_statement; 70, 71; 70, 74; 71, comparison_operator:>=; 71, 72; 71, 73; 72, identifier:verbose; 73, integer:2; 74, block; 74, 75; 74, 80; 74, 85; 74, 90; 75, expression_statement; 75, 76; 76, call; 76, 77; 76, 78; 77, identifier:print; 78, argument_list; 78, 79; 79, string:'+=== START CMD2 ==='; 80, expression_statement; 80, 81; 81, call; 81, 82; 81, 83; 82, identifier:print; 83, argument_list; 83, 84; 84, string:'Command:'; 85, expression_statement; 85, 86; 86, call; 86, 87; 86, 88; 87, identifier:print; 88, argument_list; 88, 89; 89, identifier:command; 90, if_statement; 90, 91; 90, 92; 91, identifier:verbout; 92, block; 92, 93; 92, 98; 93, expression_statement; 93, 94; 94, call; 94, 95; 94, 96; 95, identifier:print; 96, argument_list; 96, 97; 97, string:'----'; 98, expression_statement; 98, 99; 99, call; 99, 100; 99, 101; 100, identifier:print; 101, argument_list; 101, 102; 102, string:'Stdout:'; 103, expression_statement; 103, 104; 104, assignment; 104, 105; 104, 106; 105, identifier:proc; 106, call; 106, 107; 106, 110; 107, attribute; 107, 108; 107, 109; 108, identifier:subprocess; 109, identifier:Popen; 110, argument_list; 110, 111; 110, 112; 110, 117; 110, 122; 110, 125; 111, identifier:args; 112, keyword_argument; 112, 113; 112, 114; 113, identifier:stdout; 114, attribute; 114, 115; 114, 116; 115, identifier:subprocess; 116, identifier:PIPE; 117, keyword_argument; 117, 118; 117, 119; 118, identifier:stderr; 119, attribute; 119, 120; 119, 121; 120, identifier:subprocess; 121, identifier:STDOUT; 122, keyword_argument; 122, 123; 122, 124; 123, identifier:shell; 124, identifier:shell; 125, keyword_argument; 125, 126; 125, 127; 126, identifier:universal_newlines; 127, True; 128, if_statement; 128, 129; 128, 130; 128, 138; 129, identifier:detatch; 130, block; 130, 131; 131, expression_statement; 131, 132; 132, assignment; 132, 133; 132, 134; 133, identifier:info; 134, dictionary; 134, 135; 135, pair; 135, 136; 135, 137; 136, string:'proc'; 137, identifier:proc; 138, else_clause; 138, 139; 139, block; 139, 140; 139, 148; 139, 156; 139, 160; 139, 204; 139, 252; 139, 262; 139, 270; 140, expression_statement; 140, 141; 141, assignment; 141, 142; 141, 143; 142, identifier:write_fn; 143, attribute; 143, 144; 143, 147; 144, attribute; 144, 145; 144, 146; 145, identifier:sys; 146, identifier:stdout; 147, identifier:write; 148, expression_statement; 148, 149; 149, assignment; 149, 150; 149, 151; 150, identifier:flush_fn; 151, attribute; 151, 152; 151, 155; 152, attribute; 152, 153; 152, 154; 153, identifier:sys; 154, identifier:stdout; 155, identifier:flush; 156, expression_statement; 156, 157; 157, assignment; 157, 158; 157, 159; 158, identifier:logged_out; 159, list:[]; 160, for_statement; 160, 161; 160, 162; 160, 166; 160, 167; 161, identifier:line; 162, call; 162, 163; 162, 164; 163, identifier:_run_process; 164, argument_list; 164, 165; 165, identifier:proc; 166, comment; 167, block; 167, 168; 167, 177; 168, expression_statement; 168, 169; 169, assignment; 169, 170; 169, 171; 170, identifier:line_; 171, conditional_expression:if; 171, 172; 171, 173; 171, 176; 172, identifier:line; 173, attribute; 173, 174; 173, 175; 174, identifier:six; 175, identifier:PY2; 176, identifier:line; 177, if_statement; 177, 178; 177, 184; 178, comparison_operator:>; 178, 179; 178, 183; 179, call; 179, 180; 179, 181; 180, identifier:len; 181, argument_list; 181, 182; 182, identifier:line_; 183, integer:0; 184, block; 184, 185; 184, 197; 185, if_statement; 185, 186; 185, 187; 186, identifier:verbout; 187, block; 187, 188; 187, 193; 188, expression_statement; 188, 189; 189, call; 189, 190; 189, 191; 190, identifier:write_fn; 191, argument_list; 191, 192; 192, identifier:line_; 193, expression_statement; 193, 194; 194, call; 194, 195; 194, 196; 195, identifier:flush_fn; 196, argument_list; 197, expression_statement; 197, 198; 198, call; 198, 199; 198, 202; 199, attribute; 199, 200; 199, 201; 200, identifier:logged_out; 201, identifier:append; 202, argument_list; 202, 203; 203, identifier:line; 204, try_statement; 204, 205; 204, 222; 205, block; 205, 206; 205, 211; 205, 212; 205, 213; 206, import_from_statement; 206, 207; 206, 209; 207, dotted_name; 207, 208; 208, identifier:utool; 209, dotted_name; 209, 210; 210, identifier:util_str; 211, comment; 212, comment; 213, expression_statement; 213, 214; 214, assignment; 214, 215; 214, 216; 215, identifier:out; 216, call; 216, 217; 216, 220; 217, attribute; 217, 218; 217, 219; 218, string:''; 219, identifier:join; 220, argument_list; 220, 221; 221, identifier:logged_out; 222, except_clause; 222, 223; 222, 224; 223, identifier:UnicodeDecodeError; 224, block; 224, 225; 224, 230; 224, 231; 224, 240; 224, 241; 224, 250; 224, 251; 225, import_from_statement; 225, 226; 225, 228; 226, dotted_name; 226, 227; 227, identifier:utool; 228, dotted_name; 228, 229; 229, identifier:util_str; 230, comment; 231, expression_statement; 231, 232; 232, assignment; 232, 233; 232, 234; 233, identifier:logged_out; 234, call; 234, 235; 234, 238; 235, attribute; 235, 236; 235, 237; 236, identifier:util_str; 237, identifier:ensure_unicode_strlist; 238, argument_list; 238, 239; 239, identifier:logged_out; 240, comment; 241, expression_statement; 241, 242; 242, assignment; 242, 243; 242, 244; 243, identifier:out; 244, call; 244, 245; 244, 248; 245, attribute; 245, 246; 245, 247; 246, string:''; 247, identifier:join; 248, argument_list; 248, 249; 249, identifier:logged_out; 250, comment; 251, comment; 252, expression_statement; 252, 253; 253, assignment; 253, 254; 253, 257; 254, tuple_pattern; 254, 255; 254, 256; 255, identifier:out_; 256, identifier:err; 257, call; 257, 258; 257, 261; 258, attribute; 258, 259; 258, 260; 259, identifier:proc; 260, identifier:communicate; 261, argument_list; 262, expression_statement; 262, 263; 263, assignment; 263, 264; 263, 265; 264, identifier:ret; 265, call; 265, 266; 265, 269; 266, attribute; 266, 267; 266, 268; 267, identifier:proc; 268, identifier:wait; 269, argument_list; 270, expression_statement; 270, 271; 271, assignment; 271, 272; 271, 273; 272, identifier:info; 273, dictionary; 273, 274; 273, 277; 273, 280; 274, pair; 274, 275; 274, 276; 275, string:'out'; 276, identifier:out; 277, pair; 277, 278; 277, 279; 278, string:'err'; 279, identifier:err; 280, pair; 280, 281; 280, 282; 281, string:'ret'; 282, identifier:ret; 283, if_statement; 283, 284; 283, 287; 284, comparison_operator:>=; 284, 285; 284, 286; 285, identifier:verbose; 286, integer:2; 287, block; 287, 288; 288, expression_statement; 288, 289; 289, call; 289, 290; 289, 291; 290, identifier:print; 291, argument_list; 291, 292; 292, string:'L___ END CMD2 ___'; 293, return_statement; 293, 294; 294, identifier:info
def cmd2(command, shell=False, detatch=False, verbose=False, verbout=None): """ Trying to clean up cmd Args: command (str): string command shell (bool): if True, process is run in shell detatch (bool): if True, process is run in background verbose (int): verbosity mode verbout (bool): if True, `command` writes to stdout in realtime. defaults to True iff verbose > 0 Returns: dict: info - information about command status """ import shlex if isinstance(command, (list, tuple)): raise ValueError('command tuple not supported yet') args = shlex.split(command, posix=not WIN32) if verbose is True: verbose = 2 if verbout is None: verbout = verbose >= 1 if verbose >= 2: print('+=== START CMD2 ===') print('Command:') print(command) if verbout: print('----') print('Stdout:') proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=shell, universal_newlines=True) if detatch: info = {'proc': proc} else: write_fn = sys.stdout.write flush_fn = sys.stdout.flush logged_out = [] for line in _run_process(proc): #line_ = line if six.PY2 else line.decode('utf-8') line_ = line if six.PY2 else line if len(line_) > 0: if verbout: write_fn(line_) flush_fn() logged_out.append(line) try: from utool import util_str # NOQA # out = '\n'.join(logged_out) out = ''.join(logged_out) except UnicodeDecodeError: from utool import util_str # NOQA logged_out = util_str.ensure_unicode_strlist(logged_out) # out = '\n'.join(logged_out) out = ''.join(logged_out) # print('logged_out = %r' % (logged_out,)) # raise (out_, err) = proc.communicate() ret = proc.wait() info = { 'out': out, 'err': err, 'ret': ret, } if verbose >= 2: print('L___ END CMD2 ___') return info
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 11; 2, function_name:search_env_paths; 3, parameters; 3, 4; 3, 5; 3, 8; 4, identifier:fname; 5, default_parameter; 5, 6; 5, 7; 6, identifier:key_list; 7, None; 8, default_parameter; 8, 9; 8, 10; 9, identifier:verbose; 10, None; 11, block; 11, 12; 11, 14; 11, 19; 11, 20; 11, 53; 11, 62; 11, 115; 12, expression_statement; 12, 13; 13, comment; 14, import_statement; 14, 15; 15, aliased_import; 15, 16; 15, 18; 16, dotted_name; 16, 17; 17, identifier:utool; 18, identifier:ut; 19, comment; 20, if_statement; 20, 21; 20, 24; 21, comparison_operator:is; 21, 22; 21, 23; 22, identifier:key_list; 23, None; 24, block; 24, 25; 24, 45; 25, expression_statement; 25, 26; 26, assignment; 26, 27; 26, 28; 27, identifier:key_list; 28, list_comprehension; 28, 29; 28, 30; 28, 35; 29, identifier:key; 30, for_in_clause; 30, 31; 30, 32; 31, identifier:key; 32, attribute; 32, 33; 32, 34; 33, identifier:os; 34, identifier:environ; 35, if_clause; 35, 36; 36, comparison_operator:>; 36, 37; 36, 43; 37, call; 37, 38; 37, 41; 38, attribute; 38, 39; 38, 40; 39, identifier:key; 40, identifier:find; 41, argument_list; 41, 42; 42, string:'PATH'; 43, unary_operator:-; 43, 44; 44, integer:1; 45, expression_statement; 45, 46; 46, call; 46, 47; 46, 48; 47, identifier:print; 48, argument_list; 48, 49; 49, binary_operator:%; 49, 50; 49, 51; 50, string:'key_list = %r'; 51, tuple; 51, 52; 52, identifier:key_list; 53, expression_statement; 53, 54; 54, assignment; 54, 55; 54, 56; 55, identifier:found; 56, call; 56, 57; 56, 60; 57, attribute; 57, 58; 57, 59; 58, identifier:ut; 59, identifier:ddict; 60, argument_list; 60, 61; 61, identifier:list; 62, for_statement; 62, 63; 62, 64; 62, 65; 63, identifier:key; 64, identifier:key_list; 65, block; 65, 66; 65, 81; 66, expression_statement; 66, 67; 67, assignment; 67, 68; 67, 69; 68, identifier:dpath_list; 69, call; 69, 70; 69, 77; 70, attribute; 70, 71; 70, 76; 71, subscript; 71, 72; 71, 75; 72, attribute; 72, 73; 72, 74; 73, identifier:os; 74, identifier:environ; 75, identifier:key; 76, identifier:split; 77, argument_list; 77, 78; 78, attribute; 78, 79; 78, 80; 79, identifier:os; 80, identifier:pathsep; 81, for_statement; 81, 82; 81, 83; 81, 84; 81, 85; 81, 86; 81, 87; 82, identifier:dpath; 83, identifier:dpath_list; 84, comment; 85, comment; 86, comment; 87, block; 87, 88; 87, 98; 87, 107; 87, 108; 87, 109; 87, 110; 87, 111; 87, 112; 87, 113; 87, 114; 88, expression_statement; 88, 89; 89, assignment; 89, 90; 89, 91; 90, identifier:matches; 91, call; 91, 92; 91, 95; 92, attribute; 92, 93; 92, 94; 93, identifier:ut; 94, identifier:glob; 95, argument_list; 95, 96; 95, 97; 96, identifier:dpath; 97, identifier:fname; 98, expression_statement; 98, 99; 99, call; 99, 100; 99, 105; 100, attribute; 100, 101; 100, 104; 101, subscript; 101, 102; 101, 103; 102, identifier:found; 103, identifier:key; 104, identifier:extend; 105, argument_list; 105, 106; 106, identifier:matches; 107, comment; 108, comment; 109, comment; 110, comment; 111, comment; 112, comment; 113, comment; 114, comment; 115, return_statement; 115, 116; 116, call; 116, 117; 116, 118; 117, identifier:dict; 118, argument_list; 118, 119; 119, identifier:found
def search_env_paths(fname, key_list=None, verbose=None): r""" Searches your PATH to see if fname exists Args: fname (str): file name to search for (can be glob pattern) CommandLine: python -m utool search_env_paths --fname msvcr*.dll python -m utool search_env_paths --fname '*flann*' Example: >>> # DISABLE_DOCTEST >>> from utool.util_cplat import * # NOQA >>> import utool as ut >>> fname = 'opencv2/highgui/libopencv_highgui.so' >>> fname = ut.get_argval('--fname', default='*') >>> print('fname = %r' % (fname,)) >>> key_list = None # ['PATH'] >>> found = search_env_paths(fname, key_list) >>> print(ut.repr4(found, nl=True, strvals=True)) Ignore: OpenCV_DIR:PATH={share_opencv} OpenCV_CONFIG_PATH:FILEPATH={share_opencv} """ import utool as ut # from os.path import join if key_list is None: key_list = [key for key in os.environ if key.find('PATH') > -1] print('key_list = %r' % (key_list,)) found = ut.ddict(list) for key in key_list: dpath_list = os.environ[key].split(os.pathsep) for dpath in dpath_list: #if verbose: # print('dpath = %r' % (dpath,)) # testname = join(dpath, fname) matches = ut.glob(dpath, fname) found[key].extend(matches) #import fnmatch #import utool #utool.embed() #if ut.checkpath(testname, verbose=False): # if verbose: # print('Found in key=%r' % (key,)) # ut.checkpath(testname, verbose=True, info=True) # found += [testname] return dict(found)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 11; 2, function_name:partition_varied_cfg_list; 3, parameters; 3, 4; 3, 5; 3, 8; 4, identifier:cfg_list; 5, default_parameter; 5, 6; 5, 7; 6, identifier:default_cfg; 7, None; 8, default_parameter; 8, 9; 8, 10; 9, identifier:recursive; 10, False; 11, block; 11, 12; 11, 14; 11, 19; 11, 49; 11, 60; 11, 78; 11, 186; 12, expression_statement; 12, 13; 13, comment; 14, import_statement; 14, 15; 15, aliased_import; 15, 16; 15, 18; 16, dotted_name; 16, 17; 17, identifier:utool; 18, identifier:ut; 19, if_statement; 19, 20; 19, 23; 19, 34; 20, comparison_operator:is; 20, 21; 20, 22; 21, identifier:default_cfg; 22, None; 23, block; 23, 24; 24, expression_statement; 24, 25; 25, assignment; 25, 26; 25, 27; 26, identifier:nonvaried_cfg; 27, call; 27, 28; 27, 29; 28, identifier:reduce; 29, argument_list; 29, 30; 29, 33; 30, attribute; 30, 31; 30, 32; 31, identifier:ut; 32, identifier:dict_intersection; 33, identifier:cfg_list; 34, else_clause; 34, 35; 35, block; 35, 36; 36, expression_statement; 36, 37; 37, assignment; 37, 38; 37, 39; 38, identifier:nonvaried_cfg; 39, call; 39, 40; 39, 41; 40, identifier:reduce; 41, argument_list; 41, 42; 41, 45; 42, attribute; 42, 43; 42, 44; 43, identifier:ut; 44, identifier:dict_intersection; 45, binary_operator:+; 45, 46; 45, 48; 46, list:[default_cfg]; 46, 47; 47, identifier:default_cfg; 48, identifier:cfg_list; 49, expression_statement; 49, 50; 50, assignment; 50, 51; 50, 52; 51, identifier:nonvaried_keys; 52, call; 52, 53; 52, 54; 53, identifier:list; 54, argument_list; 54, 55; 55, call; 55, 56; 55, 59; 56, attribute; 56, 57; 56, 58; 57, identifier:nonvaried_cfg; 58, identifier:keys; 59, argument_list; 60, expression_statement; 60, 61; 61, assignment; 61, 62; 61, 63; 62, identifier:varied_cfg_list; 63, list_comprehension; 63, 64; 63, 75; 64, call; 64, 65; 64, 68; 65, attribute; 65, 66; 65, 67; 66, identifier:ut; 67, identifier:delete_dict_keys; 68, argument_list; 68, 69; 68, 74; 69, call; 69, 70; 69, 73; 70, attribute; 70, 71; 70, 72; 71, identifier:cfg; 72, identifier:copy; 73, argument_list; 74, identifier:nonvaried_keys; 75, for_in_clause; 75, 76; 75, 77; 76, identifier:cfg; 77, identifier:cfg_list; 78, if_statement; 78, 79; 78, 80; 78, 81; 79, identifier:recursive; 80, comment; 81, block; 81, 82; 81, 99; 81, 117; 82, expression_statement; 82, 83; 83, assignment; 83, 84; 83, 85; 84, identifier:varied_keys; 85, call; 85, 86; 85, 87; 86, identifier:list; 87, argument_list; 87, 88; 88, call; 88, 89; 88, 90; 89, identifier:set; 90, argument_list; 90, 91; 91, list_comprehension; 91, 92; 91, 93; 91, 96; 92, identifier:key; 93, for_in_clause; 93, 94; 93, 95; 94, identifier:cfg; 95, identifier:varied_cfg_list; 96, for_in_clause; 96, 97; 96, 98; 97, identifier:key; 98, identifier:cfg; 99, expression_statement; 99, 100; 100, assignment; 100, 101; 100, 102; 101, identifier:varied_vals_list; 102, list_comprehension; 102, 103; 102, 114; 103, list_comprehension; 103, 104; 103, 107; 103, 110; 104, subscript; 104, 105; 104, 106; 105, identifier:cfg; 106, identifier:key; 107, for_in_clause; 107, 108; 107, 109; 108, identifier:cfg; 109, identifier:varied_cfg_list; 110, if_clause; 110, 111; 111, comparison_operator:in; 111, 112; 111, 113; 112, identifier:key; 113, identifier:cfg; 114, for_in_clause; 114, 115; 114, 116; 115, identifier:key; 116, identifier:varied_keys; 117, for_statement; 117, 118; 117, 121; 117, 126; 118, pattern_list; 118, 119; 118, 120; 119, identifier:key; 120, identifier:varied_vals; 121, call; 121, 122; 121, 123; 122, identifier:zip; 123, argument_list; 123, 124; 123, 125; 124, identifier:varied_keys; 125, identifier:varied_vals_list; 126, block; 126, 127; 127, if_statement; 127, 128; 127, 137; 128, comparison_operator:==; 128, 129; 128, 133; 129, call; 129, 130; 129, 131; 130, identifier:len; 131, argument_list; 131, 132; 132, identifier:varied_vals; 133, call; 133, 134; 133, 135; 134, identifier:len; 135, argument_list; 135, 136; 136, identifier:cfg_list; 137, block; 137, 138; 138, if_statement; 138, 139; 138, 151; 139, call; 139, 140; 139, 141; 140, identifier:all; 141, argument_list; 141, 142; 142, list_comprehension; 142, 143; 142, 148; 143, call; 143, 144; 143, 145; 144, identifier:isinstance; 145, argument_list; 145, 146; 145, 147; 146, identifier:val; 147, identifier:dict; 148, for_in_clause; 148, 149; 148, 150; 149, identifier:val; 150, identifier:varied_vals; 151, block; 151, 152; 151, 164; 151, 170; 152, expression_statement; 152, 153; 153, assignment; 153, 154; 153, 157; 154, pattern_list; 154, 155; 154, 156; 155, identifier:nonvaried_subdict; 156, identifier:varied_subdicts; 157, call; 157, 158; 157, 159; 158, identifier:partition_varied_cfg_list; 159, argument_list; 159, 160; 159, 161; 160, identifier:varied_vals; 161, keyword_argument; 161, 162; 161, 163; 162, identifier:recursive; 163, identifier:recursive; 164, expression_statement; 164, 165; 165, assignment; 165, 166; 165, 169; 166, subscript; 166, 167; 166, 168; 167, identifier:nonvaried_cfg; 168, identifier:key; 169, identifier:nonvaried_subdict; 170, for_statement; 170, 171; 170, 174; 170, 179; 171, pattern_list; 171, 172; 171, 173; 172, identifier:cfg; 173, identifier:subdict; 174, call; 174, 175; 174, 176; 175, identifier:zip; 176, argument_list; 176, 177; 176, 178; 177, identifier:varied_cfg_list; 178, identifier:varied_subdicts; 179, block; 179, 180; 180, expression_statement; 180, 181; 181, assignment; 181, 182; 181, 185; 182, subscript; 182, 183; 182, 184; 183, identifier:cfg; 184, identifier:key; 185, identifier:subdict; 186, return_statement; 186, 187; 187, expression_list; 187, 188; 187, 189; 188, identifier:nonvaried_cfg; 189, identifier:varied_cfg_list
def partition_varied_cfg_list(cfg_list, default_cfg=None, recursive=False): r""" Separates varied from non-varied parameters in a list of configs TODO: partition nested configs CommandLine: python -m utool.util_gridsearch --exec-partition_varied_cfg_list:0 Example: >>> # ENABLE_DOCTEST >>> from utool.util_gridsearch import * # NOQA >>> import utool as ut >>> cfg_list = [{'f': 1, 'b': 1}, {'f': 2, 'b': 1}, {'f': 3, 'b': 1, 'z': 4}] >>> nonvaried_cfg, varied_cfg_list = partition_varied_cfg_list(cfg_list) >>> result = ut.repr4({'nonvaried_cfg': nonvaried_cfg, >>> 'varied_cfg_list': varied_cfg_list}, explicit=1, nobr=True, nl=1) >>> print(result) nonvaried_cfg={'b': 1}, varied_cfg_list=[{'f': 1}, {'f': 2}, {'f': 3, 'z': 4}], Example: >>> # ENABLE_DOCTEST >>> from utool.util_gridsearch import * # NOQA >>> import utool as ut >>> cfg_list = [{'q1': 1, 'f1': {'a2': {'x3': 1, 'y3': 2}, 'b2': 1}}, {'q1': 1, 'f1': {'a2': {'x3': 1, 'y3': 1}, 'b2': 1}, 'e1': 1}] >>> print(ut.repr4(cfg_list, nl=1)) >>> nonvaried_cfg, varied_cfg_list = partition_varied_cfg_list(cfg_list, recursive=True) >>> result = ut.repr4({'nonvaried_cfg': nonvaried_cfg, >>> 'varied_cfg_list': varied_cfg_list}, explicit=1, nobr=True, nl=1) >>> print(result) nonvaried_cfg={'f1': {'a2': {'x3': 1}, 'b2': 1}, 'q1': 1}, varied_cfg_list=[{'f1': {'a2': {'y3': 2}}}, {'e1': 1, 'f1': {'a2': {'y3': 1}}}], """ import utool as ut if default_cfg is None: nonvaried_cfg = reduce(ut.dict_intersection, cfg_list) else: nonvaried_cfg = reduce(ut.dict_intersection, [default_cfg] + cfg_list) nonvaried_keys = list(nonvaried_cfg.keys()) varied_cfg_list = [ ut.delete_dict_keys(cfg.copy(), nonvaried_keys) for cfg in cfg_list] if recursive: # Find which varied keys have dict values varied_keys = list(set([key for cfg in varied_cfg_list for key in cfg])) varied_vals_list = [[cfg[key] for cfg in varied_cfg_list if key in cfg] for key in varied_keys] for key, varied_vals in zip(varied_keys, varied_vals_list): if len(varied_vals) == len(cfg_list): if all([isinstance(val, dict) for val in varied_vals]): nonvaried_subdict, varied_subdicts = partition_varied_cfg_list(varied_vals, recursive=recursive) nonvaried_cfg[key] = nonvaried_subdict for cfg, subdict in zip(varied_cfg_list, varied_subdicts): cfg[key] = subdict return nonvaried_cfg, varied_cfg_list
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 32; 2, function_name:parse_cfgstr_list2; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 3, 14; 3, 17; 3, 20; 3, 23; 3, 26; 3, 29; 4, identifier:cfgstr_list; 5, default_parameter; 5, 6; 5, 7; 6, identifier:named_defaults_dict; 7, None; 8, default_parameter; 8, 9; 8, 10; 9, identifier:cfgtype; 10, None; 11, default_parameter; 11, 12; 11, 13; 12, identifier:alias_keys; 13, None; 14, default_parameter; 14, 15; 14, 16; 15, identifier:valid_keys; 16, None; 17, default_parameter; 17, 18; 17, 19; 18, identifier:expand_nested; 19, True; 20, default_parameter; 20, 21; 20, 22; 21, identifier:strict; 22, True; 23, default_parameter; 23, 24; 23, 25; 24, identifier:special_join_dict; 25, None; 26, default_parameter; 26, 27; 26, 28; 27, identifier:is_nestedcfgtype; 28, False; 29, default_parameter; 29, 30; 29, 31; 30, identifier:metadata; 31, None; 32, block; 32, 33; 32, 35; 32, 40; 32, 41; 32, 45; 32, 49; 32, 50; 32, 54; 32, 128; 32, 144; 32, 449; 32, 450; 32, 451; 33, expression_statement; 33, 34; 34, comment; 35, import_statement; 35, 36; 36, aliased_import; 36, 37; 36, 39; 37, dotted_name; 37, 38; 38, identifier:utool; 39, identifier:ut; 40, comment; 41, expression_statement; 41, 42; 42, assignment; 42, 43; 42, 44; 43, identifier:cfg_combos_list; 44, list:[]; 45, expression_statement; 45, 46; 46, assignment; 46, 47; 46, 48; 47, identifier:cfgstr_list_; 48, list:[]; 49, comment; 50, expression_statement; 50, 51; 51, assignment; 51, 52; 51, 53; 52, identifier:dyndef_named_defaults; 53, dictionary; 54, for_statement; 54, 55; 54, 56; 54, 57; 55, identifier:cfgstr; 56, identifier:cfgstr_list; 57, block; 57, 58; 58, if_statement; 58, 59; 58, 68; 58, 119; 59, comparison_operator:>; 59, 60; 59, 66; 60, call; 60, 61; 60, 64; 61, attribute; 61, 62; 61, 63; 62, identifier:cfgstr; 63, identifier:find; 64, argument_list; 64, 65; 65, string:'=:'; 66, unary_operator:-; 66, 67; 67, integer:1; 68, block; 68, 69; 68, 79; 68, 86; 68, 95; 68, 106; 68, 113; 69, expression_statement; 69, 70; 70, assignment; 70, 71; 70, 75; 71, pattern_list; 71, 72; 71, 73; 71, 74; 72, identifier:cfgname; 73, identifier:cfgopt_strs; 74, identifier:subx; 75, call; 75, 76; 75, 77; 76, identifier:parse_cfgstr_name_options; 77, argument_list; 77, 78; 78, identifier:cfgstr; 79, assert_statement; 79, 80; 80, call; 80, 81; 80, 84; 81, attribute; 81, 82; 81, 83; 82, identifier:cfgname; 83, identifier:endswith; 84, argument_list; 84, 85; 85, string:'='; 86, expression_statement; 86, 87; 87, assignment; 87, 88; 87, 89; 88, identifier:cfgname; 89, subscript; 89, 90; 89, 91; 90, identifier:cfgname; 91, slice; 91, 92; 91, 93; 92, colon; 93, unary_operator:-; 93, 94; 94, integer:1; 95, expression_statement; 95, 96; 96, assignment; 96, 97; 96, 98; 97, identifier:base_cfg_list; 98, call; 98, 99; 98, 100; 99, identifier:lookup_base_cfg_list; 100, argument_list; 100, 101; 100, 102; 100, 103; 101, identifier:cfgname; 102, identifier:named_defaults_dict; 103, keyword_argument; 103, 104; 103, 105; 104, identifier:metadata; 105, identifier:metadata; 106, expression_statement; 106, 107; 107, assignment; 107, 108; 107, 109; 108, identifier:cfg_options; 109, call; 109, 110; 109, 111; 110, identifier:noexpand_parse_cfgstrs; 111, argument_list; 111, 112; 112, identifier:cfgopt_strs; 113, expression_statement; 113, 114; 114, assignment; 114, 115; 114, 118; 115, subscript; 115, 116; 115, 117; 116, identifier:dyndef_named_defaults; 117, identifier:cfgname; 118, identifier:cfg_options; 119, else_clause; 119, 120; 120, block; 120, 121; 121, expression_statement; 121, 122; 122, call; 122, 123; 122, 126; 123, attribute; 123, 124; 123, 125; 124, identifier:cfgstr_list_; 125, identifier:append; 126, argument_list; 126, 127; 127, identifier:cfgstr; 128, if_statement; 128, 129; 128, 139; 129, boolean_operator:and; 129, 130; 129, 136; 130, comparison_operator:>; 130, 131; 130, 135; 131, call; 131, 132; 131, 133; 132, identifier:len; 133, argument_list; 133, 134; 134, identifier:dyndef_named_defaults; 135, integer:0; 136, comparison_operator:is; 136, 137; 136, 138; 137, identifier:named_defaults_dict; 138, None; 139, block; 139, 140; 140, expression_statement; 140, 141; 141, assignment; 141, 142; 141, 143; 142, identifier:named_defaults_dict; 143, identifier:dyndef_named_defaults; 144, for_statement; 144, 145; 144, 146; 144, 147; 145, identifier:cfgstr; 146, identifier:cfgstr_list_; 147, block; 147, 148; 147, 152; 147, 153; 147, 436; 147, 437; 147, 438; 147, 439; 148, expression_statement; 148, 149; 149, assignment; 149, 150; 149, 151; 150, identifier:cfg_combos; 151, list:[]; 152, comment; 153, if_statement; 153, 154; 153, 163; 153, 269; 154, comparison_operator:>; 154, 155; 154, 161; 155, call; 155, 156; 155, 159; 156, attribute; 156, 157; 156, 158; 157, identifier:cfgstr; 158, identifier:find; 159, argument_list; 159, 160; 160, string:'::'; 161, unary_operator:-; 161, 162; 162, integer:1; 163, block; 163, 164; 163, 173; 163, 174; 163, 205; 163, 225; 163, 246; 163, 247; 164, expression_statement; 164, 165; 165, assignment; 165, 166; 165, 167; 166, identifier:special_cfgstr_list; 167, call; 167, 168; 167, 171; 168, attribute; 168, 169; 168, 170; 169, identifier:cfgstr; 170, identifier:split; 171, argument_list; 171, 172; 172, string:'::'; 173, comment; 174, expression_statement; 174, 175; 175, assignment; 175, 176; 175, 177; 176, identifier:special_combo_list; 177, call; 177, 178; 177, 179; 178, identifier:parse_cfgstr_list2; 179, argument_list; 179, 180; 179, 181; 179, 184; 179, 187; 179, 190; 179, 193; 179, 196; 179, 199; 179, 202; 180, identifier:special_cfgstr_list; 181, keyword_argument; 181, 182; 181, 183; 182, identifier:named_defaults_dict; 183, identifier:named_defaults_dict; 184, keyword_argument; 184, 185; 184, 186; 185, identifier:cfgtype; 186, identifier:cfgtype; 187, keyword_argument; 187, 188; 187, 189; 188, identifier:alias_keys; 189, identifier:alias_keys; 190, keyword_argument; 190, 191; 190, 192; 191, identifier:valid_keys; 192, identifier:valid_keys; 193, keyword_argument; 193, 194; 193, 195; 194, identifier:strict; 195, identifier:strict; 196, keyword_argument; 196, 197; 196, 198; 197, identifier:expand_nested; 198, identifier:expand_nested; 199, keyword_argument; 199, 200; 199, 201; 200, identifier:is_nestedcfgtype; 201, False; 202, keyword_argument; 202, 203; 202, 204; 203, identifier:metadata; 204, identifier:metadata; 205, if_statement; 205, 206; 205, 209; 206, comparison_operator:is; 206, 207; 206, 208; 207, identifier:special_join_dict; 208, None; 209, block; 209, 210; 210, for_statement; 210, 211; 210, 212; 210, 213; 211, identifier:special_combo; 212, identifier:special_combo_list; 213, block; 213, 214; 214, for_statement; 214, 215; 214, 216; 214, 217; 215, identifier:cfg; 216, identifier:special_combo; 217, block; 217, 218; 218, expression_statement; 218, 219; 219, call; 219, 220; 219, 223; 220, attribute; 220, 221; 220, 222; 221, identifier:cfg; 222, identifier:update; 223, argument_list; 223, 224; 224, identifier:special_join_dict; 225, if_statement; 225, 226; 225, 227; 225, 239; 226, identifier:is_nestedcfgtype; 227, block; 227, 228; 228, expression_statement; 228, 229; 229, assignment; 229, 230; 229, 231; 230, identifier:cfg_combo; 231, call; 231, 232; 231, 233; 232, identifier:tuple; 233, argument_list; 233, 234; 234, list_comprehension; 234, 235; 234, 236; 235, identifier:combo; 236, for_in_clause; 236, 237; 236, 238; 237, identifier:combo; 238, identifier:special_combo_list; 239, else_clause; 239, 240; 239, 241; 240, comment; 241, block; 241, 242; 242, expression_statement; 242, 243; 243, assignment; 243, 244; 243, 245; 244, identifier:cfg_combo; 245, identifier:special_combo_list; 246, comment; 247, if_statement; 247, 248; 247, 249; 247, 257; 248, identifier:expand_nested; 249, block; 249, 250; 250, expression_statement; 250, 251; 251, call; 251, 252; 251, 255; 252, attribute; 252, 253; 252, 254; 253, identifier:cfg_combos; 254, identifier:extend; 255, argument_list; 255, 256; 256, identifier:cfg_combo; 257, else_clause; 257, 258; 257, 259; 257, 260; 257, 261; 258, comment; 259, comment; 260, comment; 261, block; 261, 262; 262, expression_statement; 262, 263; 263, call; 263, 264; 263, 267; 264, attribute; 264, 265; 264, 266; 265, identifier:cfg_combos_list; 266, identifier:append; 267, argument_list; 267, 268; 268, identifier:cfg_combo; 269, else_clause; 269, 270; 269, 271; 270, comment; 271, block; 271, 272; 271, 282; 271, 283; 271, 284; 271, 316; 271, 317; 272, expression_statement; 272, 273; 273, assignment; 273, 274; 273, 278; 274, pattern_list; 274, 275; 274, 276; 274, 277; 275, identifier:cfgname; 276, identifier:cfgopt_strs; 277, identifier:subx; 278, call; 278, 279; 278, 280; 279, identifier:parse_cfgstr_name_options; 280, argument_list; 280, 281; 281, identifier:cfgstr; 282, comment; 283, comment; 284, try_statement; 284, 285; 284, 297; 285, block; 285, 286; 286, expression_statement; 286, 287; 287, assignment; 287, 288; 287, 289; 288, identifier:base_cfg_list; 289, call; 289, 290; 289, 291; 290, identifier:lookup_base_cfg_list; 291, argument_list; 291, 292; 291, 293; 291, 294; 292, identifier:cfgname; 293, identifier:named_defaults_dict; 294, keyword_argument; 294, 295; 294, 296; 295, identifier:metadata; 296, identifier:metadata; 297, except_clause; 297, 298; 297, 302; 298, as_pattern; 298, 299; 298, 300; 299, identifier:Exception; 300, as_pattern_target; 300, 301; 301, identifier:ex; 302, block; 302, 303; 302, 315; 303, expression_statement; 303, 304; 304, call; 304, 305; 304, 308; 305, attribute; 305, 306; 305, 307; 306, identifier:ut; 307, identifier:printex; 308, argument_list; 308, 309; 308, 310; 309, identifier:ex; 310, keyword_argument; 310, 311; 310, 312; 311, identifier:keys; 312, list:['cfgstr_list', 'cfgstr_list_']; 312, 313; 312, 314; 313, string:'cfgstr_list'; 314, string:'cfgstr_list_'; 315, raise_statement; 316, comment; 317, for_statement; 317, 318; 317, 319; 317, 320; 318, identifier:base_cfg; 319, identifier:base_cfg_list; 320, block; 320, 321; 320, 329; 320, 337; 320, 345; 320, 353; 320, 361; 320, 372; 320, 380; 320, 388; 320, 409; 320, 417; 321, expression_statement; 321, 322; 322, call; 322, 323; 322, 324; 323, identifier:print; 324, argument_list; 324, 325; 325, binary_operator:%; 325, 326; 325, 327; 326, string:'cfgname = %r'; 327, tuple; 327, 328; 328, identifier:cfgname; 329, expression_statement; 329, 330; 330, call; 330, 331; 330, 332; 331, identifier:print; 332, argument_list; 332, 333; 333, binary_operator:%; 333, 334; 333, 335; 334, string:'cfgopt_strs = %r'; 335, tuple; 335, 336; 336, identifier:cfgopt_strs; 337, expression_statement; 337, 338; 338, call; 338, 339; 338, 340; 339, identifier:print; 340, argument_list; 340, 341; 341, binary_operator:%; 341, 342; 341, 343; 342, string:'base_cfg = %r'; 343, tuple; 343, 344; 344, identifier:base_cfg; 345, expression_statement; 345, 346; 346, call; 346, 347; 346, 348; 347, identifier:print; 348, argument_list; 348, 349; 349, binary_operator:%; 349, 350; 349, 351; 350, string:'alias_keys = %r'; 351, tuple; 351, 352; 352, identifier:alias_keys; 353, expression_statement; 353, 354; 354, call; 354, 355; 354, 356; 355, identifier:print; 356, argument_list; 356, 357; 357, binary_operator:%; 357, 358; 357, 359; 358, string:'cfgtype = %r'; 359, tuple; 359, 360; 360, identifier:cfgtype; 361, expression_statement; 361, 362; 362, call; 362, 363; 362, 364; 363, identifier:print; 364, argument_list; 364, 365; 365, binary_operator:%; 365, 366; 365, 367; 366, string:'offset = %r'; 367, tuple; 367, 368; 368, call; 368, 369; 368, 370; 369, identifier:len; 370, argument_list; 370, 371; 371, identifier:cfg_combos; 372, expression_statement; 372, 373; 373, call; 373, 374; 373, 375; 374, identifier:print; 375, argument_list; 375, 376; 376, binary_operator:%; 376, 377; 376, 378; 377, string:'valid_keys = %r'; 378, tuple; 378, 379; 379, identifier:valid_keys; 380, expression_statement; 380, 381; 381, call; 381, 382; 381, 383; 382, identifier:print; 383, argument_list; 383, 384; 384, binary_operator:%; 384, 385; 384, 386; 385, string:'strict = %r'; 386, tuple; 386, 387; 387, identifier:strict; 388, expression_statement; 388, 389; 389, assignment; 389, 390; 389, 391; 390, identifier:cfg_combo; 391, call; 391, 392; 391, 393; 392, identifier:customize_base_cfg; 393, argument_list; 393, 394; 393, 395; 393, 396; 393, 397; 393, 398; 393, 399; 393, 400; 393, 403; 394, identifier:cfgname; 395, identifier:cfgopt_strs; 396, identifier:base_cfg; 397, identifier:cfgtype; 398, identifier:alias_keys; 399, identifier:valid_keys; 400, keyword_argument; 400, 401; 400, 402; 401, identifier:strict; 402, identifier:strict; 403, keyword_argument; 403, 404; 403, 405; 404, identifier:offset; 405, call; 405, 406; 405, 407; 406, identifier:len; 407, argument_list; 407, 408; 408, identifier:cfg_combos; 409, if_statement; 409, 410; 409, 411; 410, identifier:is_nestedcfgtype; 411, block; 411, 412; 412, expression_statement; 412, 413; 413, assignment; 413, 414; 413, 415; 414, identifier:cfg_combo; 415, list:[cfg_combo]; 415, 416; 416, identifier:cfg_combo; 417, if_statement; 417, 418; 417, 419; 417, 427; 418, identifier:expand_nested; 419, block; 419, 420; 420, expression_statement; 420, 421; 421, call; 421, 422; 421, 425; 422, attribute; 422, 423; 422, 424; 423, identifier:cfg_combos; 424, identifier:extend; 425, argument_list; 425, 426; 426, identifier:cfg_combo; 427, else_clause; 427, 428; 428, block; 428, 429; 429, expression_statement; 429, 430; 430, call; 430, 431; 430, 434; 431, attribute; 431, 432; 431, 433; 432, identifier:cfg_combos_list; 433, identifier:append; 434, argument_list; 434, 435; 435, identifier:cfg_combo; 436, comment; 437, comment; 438, comment; 439, if_statement; 439, 440; 439, 441; 440, identifier:expand_nested; 441, block; 441, 442; 442, expression_statement; 442, 443; 443, call; 443, 444; 443, 447; 444, attribute; 444, 445; 444, 446; 445, identifier:cfg_combos_list; 446, identifier:append; 447, argument_list; 447, 448; 448, identifier:cfg_combos; 449, comment; 450, comment; 451, return_statement; 451, 452; 452, identifier:cfg_combos_list
def parse_cfgstr_list2(cfgstr_list, named_defaults_dict=None, cfgtype=None, alias_keys=None, valid_keys=None, expand_nested=True, strict=True, special_join_dict=None, is_nestedcfgtype=False, metadata=None): r""" Parses config strings. By looking up name in a dict of configs Args: cfgstr_list (list): named_defaults_dict (dict): (default = None) cfgtype (None): (default = None) alias_keys (None): (default = None) valid_keys (None): (default = None) expand_nested (bool): (default = True) strict (bool): (default = True) is_nestedcfgtype - used for annot configs so special joins arent geometrically combined Note: Normal Case: --flag name Custom Arugment Cases: --flag name:custom_key1=custom_val1,custom_key2=custom_val2 Multiple Config Case: --flag name1:custom_args1 name2:custom_args2 Multiple Config (special join) Case: (here name2 and name3 have some special interaction) --flag name1:custom_args1 name2:custom_args2::name3:custom_args3 Varied Argument Case: --flag name:key1=[val1,val2] Returns: list: cfg_combos_list CommandLine: python -m utool.util_gridsearch --test-parse_cfgstr_list2 python -m utool.util_gridsearch --test-parse_cfgstr_list2:0 python -m utool.util_gridsearch --test-parse_cfgstr_list2:1 python -m utool.util_gridsearch --test-parse_cfgstr_list2:2 Setup: >>> from utool.util_gridsearch import * # NOQA >>> import utool as ut >>> named_defaults_dict = None >>> cfgtype, alias_keys, valid_keys, metadata = None, None, None, None >>> expand_nested, is_nestedcfgtypel, strict = True, False, False Example0: >>> # ENABLE_DOCTEST >>> from utool.util_gridsearch import * # NOQA >>> import utool as ut >>> named_defaults_dict = None >>> cfgtype, alias_keys, valid_keys, metadata = None, None, None, None >>> expand_nested, is_nestedcfgtypel, strict = True, False, False >>> cfgstr_list = ['name', 'name:f=1', 'name:b=[1,2]', 'name1:f=1::name2:f=1,b=2'] >>> #cfgstr_list = ['name', 'name1:f=1::name2:f=1,b=2'] >>> special_join_dict = {'joined': True} >>> cfg_combos_list = parse_cfgstr_list2( >>> cfgstr_list, named_defaults_dict, cfgtype, alias_keys, valid_keys, >>> expand_nested, strict, special_join_dict) >>> print('b' in cfg_combos_list[2][0]) >>> print('cfg_combos_list = %s' % (ut.repr4(cfg_combos_list, nl=2),)) >>> assert 'b' in cfg_combos_list[2][0], 'second cfg[2] should vary b' >>> assert 'b' in cfg_combos_list[2][1], 'second cfg[2] should vary b' >>> print(ut.depth_profile(cfg_combos_list)) >>> cfg_list = ut.flatten(cfg_combos_list) >>> cfg_list = ut.flatten([cfg if isinstance(cfg, list) else [cfg] for cfg in cfg_list]) >>> result = ut.repr2(ut.get_varied_cfg_lbls(cfg_list)) >>> print(result) ['name:', 'name:f=1', 'name:b=1', 'name:b=2', 'name1:f=1,joined=True', 'name2:b=2,f=1,joined=True'] Example1: >>> # ENABLE_DOCTEST >>> # Allow for definition of a named default on the fly >>> cfgstr_list = ['base=:f=2,c=[1,2]', 'base:f=1', 'base:b=[1,2]'] >>> special_join_dict = None >>> cfg_combos_list = parse_cfgstr_list2( >>> cfgstr_list, named_defaults_dict, cfgtype, alias_keys, valid_keys, >>> expand_nested, strict, special_join_dict) >>> print('cfg_combos_list = %s' % (ut.repr4(cfg_combos_list, nl=2),)) >>> print(ut.depth_profile(cfg_combos_list)) >>> cfg_list = ut.flatten(cfg_combos_list) >>> cfg_list = ut.flatten([cfg if isinstance(cfg, list) else [cfg] for cfg in cfg_list]) >>> result = ut.repr2(ut.get_varied_cfg_lbls(cfg_list)) >>> print(result) ['base:c=1,f=1', 'base:c=2,f=1', 'base:b=1,c=1,f=2', 'base:b=1,c=2,f=2', 'base:b=2,c=1,f=2', 'base:b=2,c=2,f=2'] Example2: >>> # ENABLE_DOCTEST >>> cfgstr_list = ['base:f=2,c=[(1,2),(3,4)]'] >>> special_join_dict = None >>> cfg_combos_list = parse_cfgstr_list2( >>> cfgstr_list, named_defaults_dict, cfgtype, alias_keys, valid_keys, >>> expand_nested, strict, special_join_dict) >>> print('cfg_combos_list = %s' % (ut.repr4(cfg_combos_list, nl=2),)) >>> print(ut.depth_profile(cfg_combos_list)) >>> cfg_list = ut.flatten(cfg_combos_list) >>> cfg_list = ut.flatten([cfg if isinstance(cfg, list) else [cfg] for cfg in cfg_list]) >>> result = ut.repr2(ut.get_varied_cfg_lbls(cfg_list)) >>> print(result) Example3: >>> # ENABLE_DOCTEST >>> from utool.util_gridsearch import * # NOQA >>> import utool as ut >>> named_defaults_dict = None >>> cfgtype, alias_keys, valid_keys, metadata = None, None, None, None >>> expand_nested, is_nestedcfgtypel, strict = True, False, False >>> # test simplest case >>> cfgstr_list = ['name:b=[1,2]'] >>> special_join_dict = {'joined': True} >>> cfg_combos_list = parse_cfgstr_list2( >>> cfgstr_list, named_defaults_dict, cfgtype, alias_keys, valid_keys, >>> expand_nested, strict, special_join_dict) >>> print('b' in cfg_combos_list[0][0]) >>> print('cfg_combos_list = %s' % (ut.repr4(cfg_combos_list, nl=2),)) >>> assert 'b' in cfg_combos_list[0][0], 'second cfg[2] should vary b' >>> assert 'b' in cfg_combos_list[0][1], 'second cfg[2] should vary b' >>> print(ut.depth_profile(cfg_combos_list)) >>> cfg_list = ut.flatten(cfg_combos_list) >>> cfg_list = ut.flatten([cfg if isinstance(cfg, list) else [cfg] for cfg in cfg_list]) >>> result = ut.repr2(ut.get_varied_cfg_lbls(cfg_list)) >>> print(result) """ import utool as ut #with ut.Indenter(' '): cfg_combos_list = [] cfgstr_list_ = [] # special named defaults assignment dyndef_named_defaults = {} for cfgstr in cfgstr_list: if cfgstr.find('=:') > -1: cfgname, cfgopt_strs, subx = parse_cfgstr_name_options(cfgstr) assert cfgname.endswith('=') cfgname = cfgname[:-1] base_cfg_list = lookup_base_cfg_list(cfgname, named_defaults_dict, metadata=metadata) cfg_options = noexpand_parse_cfgstrs(cfgopt_strs) dyndef_named_defaults[cfgname] = cfg_options else: cfgstr_list_.append(cfgstr) if len(dyndef_named_defaults) > 0 and named_defaults_dict is None: named_defaults_dict = dyndef_named_defaults for cfgstr in cfgstr_list_: cfg_combos = [] # Parse special joined cfg case if cfgstr.find('::') > -1: special_cfgstr_list = cfgstr.split('::') # Recursive call special_combo_list = parse_cfgstr_list2( special_cfgstr_list, named_defaults_dict=named_defaults_dict, cfgtype=cfgtype, alias_keys=alias_keys, valid_keys=valid_keys, strict=strict, expand_nested=expand_nested, is_nestedcfgtype=False, metadata=metadata) if special_join_dict is not None: for special_combo in special_combo_list: for cfg in special_combo: cfg.update(special_join_dict) if is_nestedcfgtype: cfg_combo = tuple([combo for combo in special_combo_list]) else: # not sure if this is right cfg_combo = special_combo_list # FIXME DUPLICATE CODE if expand_nested: cfg_combos.extend(cfg_combo) else: #print('Appending: ' + str(ut.depth_profile(cfg_combo))) #if ut.depth_profile(cfg_combo) == [1, 9]: # ut.embed() cfg_combos_list.append(cfg_combo) else: # Normal Case cfgname, cfgopt_strs, subx = parse_cfgstr_name_options(cfgstr) # -- # Lookup named default settings try: base_cfg_list = lookup_base_cfg_list(cfgname, named_defaults_dict, metadata=metadata) except Exception as ex: ut.printex(ex, keys=['cfgstr_list', 'cfgstr_list_']) raise # -- for base_cfg in base_cfg_list: print('cfgname = %r' % (cfgname,)) print('cfgopt_strs = %r' % (cfgopt_strs,)) print('base_cfg = %r' % (base_cfg,)) print('alias_keys = %r' % (alias_keys,)) print('cfgtype = %r' % (cfgtype,)) print('offset = %r' % (len(cfg_combos),)) print('valid_keys = %r' % (valid_keys,)) print('strict = %r' % (strict,)) cfg_combo = customize_base_cfg( cfgname, cfgopt_strs, base_cfg, cfgtype, alias_keys, valid_keys, strict=strict, offset=len(cfg_combos)) if is_nestedcfgtype: cfg_combo = [cfg_combo] if expand_nested: cfg_combos.extend(cfg_combo) else: cfg_combos_list.append(cfg_combo) # SUBX Cannot work here because of acfg hackiness #if subx is not None: # cfg_combo = ut.take(cfg_combo, subx) if expand_nested: cfg_combos_list.append(cfg_combos) # print('Updated to: ' + str(ut.depth_profile(cfg_combos_list))) #print('Returning len(cfg_combos_list) = %r' % (len(cfg_combos_list),)) return cfg_combos_list
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 11; 2, function_name:gridsearch_timer; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 4, identifier:func_list; 5, identifier:args_list; 6, default_parameter; 6, 7; 6, 8; 7, identifier:niters; 8, None; 9, dictionary_splat_pattern; 9, 10; 10, identifier:searchkw; 11, block; 11, 12; 11, 14; 11, 19; 11, 28; 11, 40; 11, 60; 11, 61; 11, 80; 11, 98; 11, 108; 11, 118; 11, 122; 11, 134; 11, 297; 11, 303; 11, 317; 11, 332; 11, 382; 11, 392; 12, expression_statement; 12, 13; 13, comment; 14, import_statement; 14, 15; 15, aliased_import; 15, 16; 15, 18; 16, dotted_name; 16, 17; 17, identifier:utool; 18, identifier:ut; 19, expression_statement; 19, 20; 20, assignment; 20, 21; 20, 22; 21, identifier:timings; 22, call; 22, 23; 22, 26; 23, attribute; 23, 24; 23, 25; 24, identifier:ut; 25, identifier:ddict; 26, argument_list; 26, 27; 27, identifier:list; 28, if_statement; 28, 29; 28, 32; 29, comparison_operator:is; 29, 30; 29, 31; 30, identifier:niters; 31, None; 32, block; 32, 33; 33, expression_statement; 33, 34; 34, assignment; 34, 35; 34, 36; 35, identifier:niters; 36, call; 36, 37; 36, 38; 37, identifier:len; 38, argument_list; 38, 39; 39, identifier:args_list; 40, if_statement; 40, 41; 40, 47; 40, 52; 41, call; 41, 42; 41, 45; 42, attribute; 42, 43; 42, 44; 43, identifier:ut; 44, identifier:is_funclike; 45, argument_list; 45, 46; 46, identifier:args_list; 47, block; 47, 48; 48, expression_statement; 48, 49; 49, assignment; 49, 50; 49, 51; 50, identifier:get_args; 51, identifier:args_list; 52, else_clause; 52, 53; 53, block; 53, 54; 54, expression_statement; 54, 55; 55, assignment; 55, 56; 55, 57; 56, identifier:get_args; 57, attribute; 57, 58; 57, 59; 58, identifier:args_list; 59, identifier:__getitem__; 60, comment; 61, expression_statement; 61, 62; 62, assignment; 62, 63; 62, 64; 63, identifier:func_labels; 64, call; 64, 65; 64, 68; 65, attribute; 65, 66; 65, 67; 66, identifier:searchkw; 67, identifier:get; 68, argument_list; 68, 69; 68, 70; 69, string:'func_labels'; 70, list_comprehension; 70, 71; 70, 77; 71, call; 71, 72; 71, 75; 72, attribute; 72, 73; 72, 74; 73, identifier:ut; 74, identifier:get_funcname; 75, argument_list; 75, 76; 76, identifier:func; 77, for_in_clause; 77, 78; 77, 79; 78, identifier:func; 79, identifier:func_list; 80, expression_statement; 80, 81; 81, assignment; 81, 82; 81, 83; 82, identifier:use_cache; 83, call; 83, 84; 83, 87; 84, attribute; 84, 85; 84, 86; 85, identifier:searchkw; 86, identifier:get; 87, argument_list; 87, 88; 87, 89; 88, string:'use_cache'; 89, not_operator; 89, 90; 90, call; 90, 91; 90, 94; 91, attribute; 91, 92; 91, 93; 92, identifier:ut; 93, identifier:get_argflag; 94, argument_list; 94, 95; 95, tuple; 95, 96; 95, 97; 96, string:'--nocache'; 97, string:'--nocache-time'; 98, expression_statement; 98, 99; 99, assignment; 99, 100; 99, 101; 100, identifier:assert_eq; 101, call; 101, 102; 101, 105; 102, attribute; 102, 103; 102, 104; 103, identifier:searchkw; 104, identifier:get; 105, argument_list; 105, 106; 105, 107; 106, string:'assert_eq'; 107, True; 108, expression_statement; 108, 109; 109, assignment; 109, 110; 109, 111; 110, identifier:count_list; 111, call; 111, 112; 111, 113; 112, identifier:list; 113, argument_list; 113, 114; 114, call; 114, 115; 114, 116; 115, identifier:range; 116, argument_list; 116, 117; 117, identifier:niters; 118, expression_statement; 118, 119; 119, assignment; 119, 120; 119, 121; 120, identifier:xlabel_list; 121, list:[]; 122, expression_statement; 122, 123; 123, assignment; 123, 124; 123, 125; 124, identifier:cache; 125, call; 125, 126; 125, 129; 126, attribute; 126, 127; 126, 128; 127, identifier:ut; 128, identifier:ShelfCacher; 129, argument_list; 129, 130; 129, 131; 130, string:'timeings.shelf'; 131, keyword_argument; 131, 132; 131, 133; 132, identifier:enabled; 133, identifier:use_cache; 134, for_statement; 134, 135; 134, 136; 134, 145; 135, identifier:count; 136, call; 136, 137; 136, 140; 137, attribute; 137, 138; 137, 139; 138, identifier:ut; 139, identifier:ProgressIter; 140, argument_list; 140, 141; 140, 142; 141, identifier:count_list; 142, keyword_argument; 142, 143; 142, 144; 143, identifier:lbl; 144, string:'Testing Timeings'; 145, block; 145, 146; 145, 153; 145, 160; 145, 178; 145, 185; 145, 189; 145, 277; 146, expression_statement; 146, 147; 147, assignment; 147, 148; 147, 149; 148, identifier:args_; 149, call; 149, 150; 149, 151; 150, identifier:get_args; 151, argument_list; 151, 152; 152, identifier:count; 153, expression_statement; 153, 154; 154, call; 154, 155; 154, 158; 155, attribute; 155, 156; 155, 157; 156, identifier:xlabel_list; 157, identifier:append; 158, argument_list; 158, 159; 159, identifier:args_; 160, if_statement; 160, 161; 160, 162; 160, 163; 160, 164; 161, True; 162, comment; 163, comment; 164, block; 164, 165; 165, if_statement; 165, 166; 165, 172; 166, not_operator; 166, 167; 167, call; 167, 168; 167, 169; 168, identifier:isinstance; 169, argument_list; 169, 170; 169, 171; 170, identifier:args_; 171, identifier:tuple; 172, block; 172, 173; 173, expression_statement; 173, 174; 174, assignment; 174, 175; 174, 176; 175, identifier:args_; 176, tuple; 176, 177; 177, identifier:args_; 178, assert_statement; 178, 179; 178, 184; 179, call; 179, 180; 179, 181; 180, identifier:isinstance; 181, argument_list; 181, 182; 181, 183; 182, identifier:args_; 183, identifier:tuple; 184, string:'args_ should be a tuple so it can be unpacked'; 185, expression_statement; 185, 186; 186, assignment; 186, 187; 186, 188; 187, identifier:ret_list; 188, list:[]; 189, for_statement; 189, 190; 189, 191; 189, 192; 190, identifier:func_; 191, identifier:func_list; 192, block; 192, 193; 192, 268; 193, try_statement; 193, 194; 193, 219; 194, block; 194, 195; 194, 199; 194, 210; 195, expression_statement; 195, 196; 196, assignment; 196, 197; 196, 198; 197, identifier:kwargs_; 198, dictionary; 199, expression_statement; 199, 200; 200, assignment; 200, 201; 200, 202; 201, identifier:func_cachekey; 202, call; 202, 203; 202, 206; 203, attribute; 203, 204; 203, 205; 204, identifier:ut; 205, identifier:get_func_result_cachekey; 206, argument_list; 206, 207; 206, 208; 206, 209; 207, identifier:func_; 208, identifier:args_; 209, identifier:kwargs_; 210, expression_statement; 210, 211; 211, assignment; 211, 212; 211, 213; 212, identifier:ellapsed; 213, call; 213, 214; 213, 217; 214, attribute; 214, 215; 214, 216; 215, identifier:cache; 216, identifier:load; 217, argument_list; 217, 218; 218, identifier:func_cachekey; 219, except_clause; 219, 220; 219, 223; 220, attribute; 220, 221; 220, 222; 221, identifier:ut; 222, identifier:CacheMissException; 223, block; 223, 224; 223, 254; 223, 260; 224, with_statement; 224, 225; 224, 238; 225, with_clause; 225, 226; 226, with_item; 226, 227; 227, as_pattern; 227, 228; 227, 236; 228, call; 228, 229; 228, 232; 229, attribute; 229, 230; 229, 231; 230, identifier:ut; 231, identifier:Timer; 232, argument_list; 232, 233; 233, keyword_argument; 233, 234; 233, 235; 234, identifier:verbose; 235, False; 236, as_pattern_target; 236, 237; 237, identifier:t; 238, block; 238, 239; 238, 247; 239, expression_statement; 239, 240; 240, assignment; 240, 241; 240, 242; 241, identifier:ret; 242, call; 242, 243; 242, 244; 243, identifier:func_; 244, argument_list; 244, 245; 245, list_splat; 245, 246; 246, identifier:args_; 247, expression_statement; 247, 248; 248, call; 248, 249; 248, 252; 249, attribute; 249, 250; 249, 251; 250, identifier:ret_list; 251, identifier:append; 252, argument_list; 252, 253; 253, identifier:ret; 254, expression_statement; 254, 255; 255, assignment; 255, 256; 255, 257; 256, identifier:ellapsed; 257, attribute; 257, 258; 257, 259; 258, identifier:t; 259, identifier:ellapsed; 260, expression_statement; 260, 261; 261, call; 261, 262; 261, 265; 262, attribute; 262, 263; 262, 264; 263, identifier:cache; 264, identifier:save; 265, argument_list; 265, 266; 265, 267; 266, identifier:func_cachekey; 267, identifier:ellapsed; 268, expression_statement; 268, 269; 269, call; 269, 270; 269, 275; 270, attribute; 270, 271; 270, 274; 271, subscript; 271, 272; 271, 273; 272, identifier:timings; 273, identifier:func_; 274, identifier:append; 275, argument_list; 275, 276; 276, identifier:ellapsed; 277, if_statement; 277, 278; 277, 279; 277, 280; 278, identifier:assert_eq; 279, comment; 280, block; 280, 281; 281, expression_statement; 281, 282; 282, call; 282, 283; 282, 286; 283, attribute; 283, 284; 283, 285; 284, identifier:ut; 285, identifier:assert_all_eq; 286, argument_list; 286, 287; 287, call; 287, 288; 287, 289; 288, identifier:list; 289, argument_list; 289, 290; 290, call; 290, 291; 290, 292; 291, identifier:map; 292, argument_list; 292, 293; 292, 296; 293, attribute; 293, 294; 293, 295; 294, identifier:ut; 295, identifier:cachestr_repr; 296, identifier:ret_list; 297, expression_statement; 297, 298; 298, call; 298, 299; 298, 302; 299, attribute; 299, 300; 299, 301; 300, identifier:cache; 301, identifier:close; 302, argument_list; 303, expression_statement; 303, 304; 304, assignment; 304, 305; 304, 306; 305, identifier:count_to_xtick; 306, call; 306, 307; 306, 310; 307, attribute; 307, 308; 307, 309; 308, identifier:searchkw; 309, identifier:get; 310, argument_list; 310, 311; 310, 312; 311, string:'count_to_xtick'; 312, lambda; 312, 313; 312, 316; 313, lambda_parameters; 313, 314; 313, 315; 314, identifier:x; 315, identifier:y; 316, identifier:x; 317, expression_statement; 317, 318; 318, assignment; 318, 319; 318, 320; 319, identifier:xtick_list; 320, list_comprehension; 320, 321; 320, 329; 321, call; 321, 322; 321, 323; 322, identifier:count_to_xtick; 323, argument_list; 323, 324; 323, 325; 324, identifier:count; 325, call; 325, 326; 325, 327; 326, identifier:get_args; 327, argument_list; 327, 328; 328, identifier:count; 329, for_in_clause; 329, 330; 329, 331; 330, identifier:count; 331, identifier:count_list; 332, function_definition; 332, 333; 332, 334; 332, 335; 333, function_name:plot_timings; 334, parameters; 335, block; 335, 336; 335, 341; 335, 351; 335, 355; 335, 359; 335, 363; 336, import_statement; 336, 337; 337, aliased_import; 337, 338; 337, 340; 338, dotted_name; 338, 339; 339, identifier:plottool; 340, identifier:pt; 341, expression_statement; 341, 342; 342, assignment; 342, 343; 342, 344; 343, identifier:ydata_list; 344, call; 344, 345; 344, 348; 345, attribute; 345, 346; 345, 347; 346, identifier:ut; 347, identifier:dict_take; 348, argument_list; 348, 349; 348, 350; 349, identifier:timings; 350, identifier:func_list; 351, expression_statement; 351, 352; 352, assignment; 352, 353; 352, 354; 353, identifier:xdata; 354, identifier:xtick_list; 355, expression_statement; 355, 356; 356, assignment; 356, 357; 356, 358; 357, identifier:ylabel; 358, string:'seconds'; 359, expression_statement; 359, 360; 360, assignment; 360, 361; 360, 362; 361, identifier:xlabel; 362, string:'input size'; 363, expression_statement; 363, 364; 364, call; 364, 365; 364, 368; 365, attribute; 365, 366; 365, 367; 366, identifier:pt; 367, identifier:multi_plot; 368, argument_list; 368, 369; 368, 370; 368, 371; 368, 374; 368, 377; 368, 380; 369, identifier:xdata; 370, identifier:ydata_list; 371, keyword_argument; 371, 372; 371, 373; 372, identifier:label_list; 373, identifier:func_labels; 374, keyword_argument; 374, 375; 374, 376; 375, identifier:ylabel; 376, identifier:ylabel; 377, keyword_argument; 377, 378; 377, 379; 378, identifier:xlabel; 379, identifier:xlabel; 380, dictionary_splat; 380, 381; 381, identifier:searchkw; 382, expression_statement; 382, 383; 383, assignment; 383, 384; 383, 385; 384, identifier:time_result; 385, dictionary; 385, 386; 385, 389; 386, pair; 386, 387; 386, 388; 387, string:'plot_timings'; 388, identifier:plot_timings; 389, pair; 389, 390; 389, 391; 390, string:'timings'; 391, identifier:timings; 392, return_statement; 392, 393; 393, identifier:time_result
def gridsearch_timer(func_list, args_list, niters=None, **searchkw): """ Times a series of functions on a series of inputs args_list is a list should vary the input sizes can also be a func that take a count param items in args_list list or returned by the func should be a tuple so it can be unpacked CommandLine: python -m ibeis.annotmatch_funcs --exec-get_annotmatch_rowids_from_aid2 --show python -m ibeis.annotmatch_funcs --exec-get_annotmatch_rowids_from_aid:1 --show Args: func_list (list): args_list (list): niters (None): (default = None) Returns: dict: time_result CommandLine: python -m utool.util_gridsearch --exec-gridsearch_timer --show Example: >>> # DISABLE_DOCTEST >>> from utool.util_gridsearch import * # NOQA >>> import utool as ut >>> func_list = [ut.fibonacci_recursive, ut.fibonacci_iterative] >>> args_list = list(range(1, 35)) >>> niters = None >>> searchkw = {} >>> time_result = gridsearch_timer(func_list, args_list, niters, **searchkw) >>> result = ('time_result = %s' % (six.text_type(time_result),)) >>> print(result) >>> time_result['plot_timings']() >>> ut.show_if_requested() """ import utool as ut timings = ut.ddict(list) if niters is None: niters = len(args_list) if ut.is_funclike(args_list): get_args = args_list else: get_args = args_list.__getitem__ #func_labels = searchkw.get('func_labels', list(range(len(func_list)))) func_labels = searchkw.get('func_labels', [ut.get_funcname(func) for func in func_list]) use_cache = searchkw.get('use_cache', not ut.get_argflag(('--nocache', '--nocache-time'))) assert_eq = searchkw.get('assert_eq', True) count_list = list(range(niters)) xlabel_list = [] cache = ut.ShelfCacher('timeings.shelf', enabled=use_cache) for count in ut.ProgressIter(count_list, lbl='Testing Timeings'): args_ = get_args(count) xlabel_list.append(args_) if True: # HACK # There is an unhandled corner case that will fail if the function expects a tuple. if not isinstance(args_, tuple): args_ = (args_,) assert isinstance(args_, tuple), 'args_ should be a tuple so it can be unpacked' ret_list = [] for func_ in func_list: try: kwargs_ = {} func_cachekey = ut.get_func_result_cachekey(func_, args_, kwargs_) ellapsed = cache.load(func_cachekey) except ut.CacheMissException: with ut.Timer(verbose=False) as t: ret = func_(*args_) ret_list.append(ret) ellapsed = t.ellapsed cache.save(func_cachekey, ellapsed) timings[func_].append(ellapsed) if assert_eq: # Hacky, not guarenteed to work if cache is one ut.assert_all_eq(list(map(ut.cachestr_repr, ret_list))) cache.close() count_to_xtick = searchkw.get('count_to_xtick', lambda x, y: x) xtick_list = [count_to_xtick(count, get_args(count)) for count in count_list] def plot_timings(): import plottool as pt ydata_list = ut.dict_take(timings, func_list) xdata = xtick_list ylabel = 'seconds' xlabel = 'input size' pt.multi_plot( xdata, ydata_list, label_list=func_labels, ylabel=ylabel, xlabel=xlabel, **searchkw ) time_result = { 'plot_timings': plot_timings, 'timings': timings, } return time_result
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 11; 2, function_name:to_string_monkey; 3, parameters; 3, 4; 3, 5; 3, 8; 4, identifier:df; 5, default_parameter; 5, 6; 5, 7; 6, identifier:highlight_cols; 7, None; 8, default_parameter; 8, 9; 8, 10; 9, identifier:latex; 10, False; 11, block; 11, 12; 11, 14; 12, expression_statement; 12, 13; 13, comment; 14, try_statement; 14, 15; 14, 426; 15, block; 15, 16; 15, 21; 15, 26; 15, 31; 15, 34; 15, 61; 15, 62; 15, 63; 15, 64; 15, 65; 15, 66; 15, 67; 15, 100; 15, 106; 15, 119; 15, 134; 15, 159; 15, 256; 15, 273; 15, 296; 15, 313; 15, 385; 15, 391; 15, 401; 15, 402; 15, 424; 16, import_statement; 16, 17; 17, aliased_import; 17, 18; 17, 20; 18, dotted_name; 18, 19; 19, identifier:pandas; 20, identifier:pd; 21, import_statement; 21, 22; 22, aliased_import; 22, 23; 22, 25; 23, dotted_name; 23, 24; 24, identifier:utool; 25, identifier:ut; 26, import_statement; 26, 27; 27, aliased_import; 27, 28; 27, 30; 28, dotted_name; 28, 29; 29, identifier:numpy; 30, identifier:np; 31, import_statement; 31, 32; 32, dotted_name; 32, 33; 33, identifier:six; 34, if_statement; 34, 35; 34, 46; 35, boolean_operator:and; 35, 36; 35, 43; 36, call; 36, 37; 36, 38; 37, identifier:isinstance; 38, argument_list; 38, 39; 38, 40; 39, identifier:highlight_cols; 40, attribute; 40, 41; 40, 42; 41, identifier:six; 42, identifier:string_types; 43, comparison_operator:==; 43, 44; 43, 45; 44, identifier:highlight_cols; 45, string:'all'; 46, block; 46, 47; 47, expression_statement; 47, 48; 48, assignment; 48, 49; 48, 50; 49, identifier:highlight_cols; 50, call; 50, 51; 50, 54; 51, attribute; 51, 52; 51, 53; 52, identifier:np; 53, identifier:arange; 54, argument_list; 54, 55; 55, call; 55, 56; 55, 57; 56, identifier:len; 57, argument_list; 57, 58; 58, attribute; 58, 59; 58, 60; 59, identifier:df; 60, identifier:columns; 61, comment; 62, comment; 63, comment; 64, comment; 65, comment; 66, comment; 67, try_statement; 67, 68; 67, 82; 68, block; 68, 69; 69, expression_statement; 69, 70; 70, assignment; 70, 71; 70, 72; 71, identifier:self; 72, call; 72, 73; 72, 80; 73, attribute; 73, 74; 73, 79; 74, attribute; 74, 75; 74, 78; 75, attribute; 75, 76; 75, 77; 76, identifier:pd; 77, identifier:formats; 78, identifier:format; 79, identifier:DataFrameFormatter; 80, argument_list; 80, 81; 81, identifier:df; 82, except_clause; 82, 83; 82, 84; 83, identifier:AttributeError; 84, block; 84, 85; 85, expression_statement; 85, 86; 86, assignment; 86, 87; 86, 88; 87, identifier:self; 88, call; 88, 89; 88, 98; 89, attribute; 89, 90; 89, 97; 90, attribute; 90, 91; 90, 96; 91, attribute; 91, 92; 91, 95; 92, attribute; 92, 93; 92, 94; 93, identifier:pd; 94, identifier:io; 95, identifier:formats; 96, identifier:format; 97, identifier:DataFrameFormatter; 98, argument_list; 98, 99; 99, identifier:df; 100, expression_statement; 100, 101; 101, assignment; 101, 102; 101, 105; 102, attribute; 102, 103; 102, 104; 103, identifier:self; 104, identifier:highlight_cols; 105, identifier:highlight_cols; 106, function_definition; 106, 107; 106, 108; 106, 110; 107, function_name:monkey; 108, parameters; 108, 109; 109, identifier:self; 110, block; 110, 111; 111, return_statement; 111, 112; 112, call; 112, 113; 112, 114; 113, identifier:monkey_to_str_columns; 114, argument_list; 114, 115; 114, 116; 115, identifier:self; 116, keyword_argument; 116, 117; 116, 118; 117, identifier:latex; 118, identifier:latex; 119, expression_statement; 119, 120; 120, call; 120, 121; 120, 124; 121, attribute; 121, 122; 121, 123; 122, identifier:ut; 123, identifier:inject_func_as_method; 124, argument_list; 124, 125; 124, 126; 124, 127; 124, 128; 124, 131; 125, identifier:self; 126, identifier:monkey; 127, string:'_to_str_columns'; 128, keyword_argument; 128, 129; 128, 130; 129, identifier:override; 130, True; 131, keyword_argument; 131, 132; 131, 133; 132, identifier:force; 133, True; 134, function_definition; 134, 135; 134, 136; 134, 138; 135, function_name:strip_ansi; 136, parameters; 136, 137; 137, identifier:text; 138, block; 138, 139; 138, 142; 138, 151; 139, import_statement; 139, 140; 140, dotted_name; 140, 141; 141, identifier:re; 142, expression_statement; 142, 143; 143, assignment; 143, 144; 143, 145; 144, identifier:ansi_escape; 145, call; 145, 146; 145, 149; 146, attribute; 146, 147; 146, 148; 147, identifier:re; 148, identifier:compile; 149, argument_list; 149, 150; 150, string:r'\x1b[^m]*m'; 151, return_statement; 151, 152; 152, call; 152, 153; 152, 156; 153, attribute; 153, 154; 153, 155; 154, identifier:ansi_escape; 155, identifier:sub; 156, argument_list; 156, 157; 156, 158; 157, string:''; 158, identifier:text; 159, function_definition; 159, 160; 159, 161; 159, 168; 160, function_name:justify_ansi; 161, parameters; 161, 162; 161, 163; 161, 164; 161, 165; 162, identifier:self; 163, identifier:texts; 164, identifier:max_len; 165, default_parameter; 165, 166; 165, 167; 166, identifier:mode; 167, string:'right'; 168, block; 168, 169; 169, if_statement; 169, 170; 169, 173; 169, 199; 169, 229; 170, comparison_operator:==; 170, 171; 170, 172; 171, identifier:mode; 172, string:'left'; 173, block; 173, 174; 174, return_statement; 174, 175; 175, list_comprehension; 175, 176; 175, 196; 176, call; 176, 177; 176, 180; 177, attribute; 177, 178; 177, 179; 178, identifier:x; 179, identifier:ljust; 180, argument_list; 180, 181; 181, binary_operator:+; 181, 182; 181, 183; 182, identifier:max_len; 183, parenthesized_expression; 183, 184; 184, binary_operator:-; 184, 185; 184, 189; 185, call; 185, 186; 185, 187; 186, identifier:len; 187, argument_list; 187, 188; 188, identifier:x; 189, call; 189, 190; 189, 191; 190, identifier:len; 191, argument_list; 191, 192; 192, call; 192, 193; 192, 194; 193, identifier:strip_ansi; 194, argument_list; 194, 195; 195, identifier:x; 196, for_in_clause; 196, 197; 196, 198; 197, identifier:x; 198, identifier:texts; 199, elif_clause; 199, 200; 199, 203; 200, comparison_operator:==; 200, 201; 200, 202; 201, identifier:mode; 202, string:'center'; 203, block; 203, 204; 204, return_statement; 204, 205; 205, list_comprehension; 205, 206; 205, 226; 206, call; 206, 207; 206, 210; 207, attribute; 207, 208; 207, 209; 208, identifier:x; 209, identifier:center; 210, argument_list; 210, 211; 211, binary_operator:+; 211, 212; 211, 213; 212, identifier:max_len; 213, parenthesized_expression; 213, 214; 214, binary_operator:-; 214, 215; 214, 219; 215, call; 215, 216; 215, 217; 216, identifier:len; 217, argument_list; 217, 218; 218, identifier:x; 219, call; 219, 220; 219, 221; 220, identifier:len; 221, argument_list; 221, 222; 222, call; 222, 223; 222, 224; 223, identifier:strip_ansi; 224, argument_list; 224, 225; 225, identifier:x; 226, for_in_clause; 226, 227; 226, 228; 227, identifier:x; 228, identifier:texts; 229, else_clause; 229, 230; 230, block; 230, 231; 231, return_statement; 231, 232; 232, list_comprehension; 232, 233; 232, 253; 233, call; 233, 234; 233, 237; 234, attribute; 234, 235; 234, 236; 235, identifier:x; 236, identifier:rjust; 237, argument_list; 237, 238; 238, binary_operator:+; 238, 239; 238, 240; 239, identifier:max_len; 240, parenthesized_expression; 240, 241; 241, binary_operator:-; 241, 242; 241, 246; 242, call; 242, 243; 242, 244; 243, identifier:len; 244, argument_list; 244, 245; 245, identifier:x; 246, call; 246, 247; 246, 248; 247, identifier:len; 248, argument_list; 248, 249; 249, call; 249, 250; 249, 251; 250, identifier:strip_ansi; 251, argument_list; 251, 252; 252, identifier:x; 253, for_in_clause; 253, 254; 253, 255; 254, identifier:x; 255, identifier:texts; 256, expression_statement; 256, 257; 257, call; 257, 258; 257, 261; 258, attribute; 258, 259; 258, 260; 259, identifier:ut; 260, identifier:inject_func_as_method; 261, argument_list; 261, 262; 261, 265; 261, 266; 261, 267; 261, 270; 262, attribute; 262, 263; 262, 264; 263, identifier:self; 264, identifier:adj; 265, identifier:justify_ansi; 266, string:'justify'; 267, keyword_argument; 267, 268; 267, 269; 268, identifier:override; 269, True; 270, keyword_argument; 270, 271; 270, 272; 271, identifier:force; 272, True; 273, function_definition; 273, 274; 273, 275; 273, 278; 274, function_name:strlen_ansii; 275, parameters; 275, 276; 275, 277; 276, identifier:self; 277, identifier:text; 278, block; 278, 279; 279, return_statement; 279, 280; 280, call; 280, 281; 280, 286; 281, attribute; 281, 282; 281, 285; 282, attribute; 282, 283; 282, 284; 283, identifier:pd; 284, identifier:compat; 285, identifier:strlen; 286, argument_list; 286, 287; 286, 291; 287, call; 287, 288; 287, 289; 288, identifier:strip_ansi; 289, argument_list; 289, 290; 290, identifier:text; 291, keyword_argument; 291, 292; 291, 293; 292, identifier:encoding; 293, attribute; 293, 294; 293, 295; 294, identifier:self; 295, identifier:encoding; 296, expression_statement; 296, 297; 297, call; 297, 298; 297, 301; 298, attribute; 298, 299; 298, 300; 299, identifier:ut; 300, identifier:inject_func_as_method; 301, argument_list; 301, 302; 301, 305; 301, 306; 301, 307; 301, 310; 302, attribute; 302, 303; 302, 304; 303, identifier:self; 304, identifier:adj; 305, identifier:strlen_ansii; 306, string:'len'; 307, keyword_argument; 307, 308; 307, 309; 308, identifier:override; 309, True; 310, keyword_argument; 310, 311; 310, 312; 311, identifier:force; 312, True; 313, if_statement; 313, 314; 313, 315; 314, False; 315, block; 315, 316; 315, 328; 315, 329; 315, 341; 315, 342; 315, 343; 315, 350; 315, 351; 315, 355; 315, 359; 315, 372; 315, 377; 316, expression_statement; 316, 317; 317, assignment; 317, 318; 317, 319; 318, identifier:strlen; 319, call; 319, 320; 319, 323; 320, attribute; 320, 321; 320, 322; 321, identifier:ut; 322, identifier:partial; 323, argument_list; 323, 324; 323, 325; 324, identifier:strlen_ansii; 325, attribute; 325, 326; 325, 327; 326, identifier:self; 327, identifier:adj; 328, comment; 329, expression_statement; 329, 330; 330, assignment; 330, 331; 330, 332; 331, identifier:justfunc; 332, call; 332, 333; 332, 336; 333, attribute; 333, 334; 333, 335; 334, identifier:ut; 335, identifier:partial; 336, argument_list; 336, 337; 336, 338; 337, identifier:justify_ansi; 338, attribute; 338, 339; 338, 340; 339, identifier:self; 340, identifier:adj; 341, comment; 342, comment; 343, expression_statement; 343, 344; 344, assignment; 344, 345; 344, 346; 345, identifier:strcols; 346, call; 346, 347; 346, 348; 347, identifier:monkey_to_str_columns; 348, argument_list; 348, 349; 349, identifier:self; 350, comment; 351, expression_statement; 351, 352; 352, assignment; 352, 353; 352, 354; 353, identifier:space; 354, integer:1; 355, expression_statement; 355, 356; 356, assignment; 356, 357; 356, 358; 357, identifier:lists; 358, identifier:strcols; 359, expression_statement; 359, 360; 360, assignment; 360, 361; 360, 362; 361, identifier:str_; 362, call; 362, 363; 362, 368; 363, attribute; 363, 364; 363, 367; 364, attribute; 364, 365; 364, 366; 365, identifier:self; 366, identifier:adj; 367, identifier:adjoin; 368, argument_list; 368, 369; 368, 370; 369, identifier:space; 370, list_splat; 370, 371; 371, identifier:lists; 372, expression_statement; 372, 373; 373, call; 373, 374; 373, 375; 374, identifier:print; 375, argument_list; 375, 376; 376, identifier:str_; 377, expression_statement; 377, 378; 378, call; 378, 379; 378, 380; 379, identifier:print; 380, argument_list; 380, 381; 381, call; 381, 382; 381, 383; 382, identifier:strip_ansi; 383, argument_list; 383, 384; 384, identifier:str_; 385, expression_statement; 385, 386; 386, call; 386, 387; 386, 390; 387, attribute; 387, 388; 387, 389; 388, identifier:self; 389, identifier:to_string; 390, argument_list; 391, expression_statement; 391, 392; 392, assignment; 392, 393; 392, 394; 393, identifier:result; 394, call; 394, 395; 394, 400; 395, attribute; 395, 396; 395, 399; 396, attribute; 396, 397; 396, 398; 397, identifier:self; 398, identifier:buf; 399, identifier:getvalue; 400, argument_list; 401, comment; 402, expression_statement; 402, 403; 403, assignment; 403, 404; 403, 405; 404, identifier:result; 405, call; 405, 406; 405, 409; 406, attribute; 406, 407; 406, 408; 407, string:'\n'; 408, identifier:join; 409, argument_list; 409, 410; 410, list_comprehension; 410, 411; 410, 416; 411, call; 411, 412; 411, 415; 412, attribute; 412, 413; 412, 414; 413, identifier:x; 414, identifier:rstrip; 415, argument_list; 416, for_in_clause; 416, 417; 416, 418; 417, identifier:x; 418, call; 418, 419; 418, 422; 419, attribute; 419, 420; 419, 421; 420, identifier:result; 421, identifier:split; 422, argument_list; 422, 423; 423, string:'\n'; 424, return_statement; 424, 425; 425, identifier:result; 426, except_clause; 426, 427; 426, 431; 427, as_pattern; 427, 428; 427, 429; 428, identifier:Exception; 429, as_pattern_target; 429, 430; 430, identifier:ex; 431, block; 431, 432; 431, 453; 432, expression_statement; 432, 433; 433, call; 433, 434; 433, 437; 434, attribute; 434, 435; 434, 436; 435, identifier:ut; 436, identifier:printex; 437, argument_list; 437, 438; 437, 447; 437, 450; 438, call; 438, 439; 438, 442; 439, attribute; 439, 440; 439, 441; 440, string:'pandas monkey-patch is broken: {}'; 441, identifier:format; 442, argument_list; 442, 443; 443, call; 443, 444; 443, 445; 444, identifier:str; 445, argument_list; 445, 446; 446, identifier:ex; 447, keyword_argument; 447, 448; 447, 449; 448, identifier:tb; 449, True; 450, keyword_argument; 450, 451; 450, 452; 451, identifier:iswarning; 452, True; 453, return_statement; 453, 454; 454, call; 454, 455; 454, 456; 455, identifier:str; 456, argument_list; 456, 457; 457, identifier:df
def to_string_monkey(df, highlight_cols=None, latex=False): """ monkey patch to pandas to highlight the maximum value in specified cols of a row Example: >>> from utool.experimental.pandas_highlight import * >>> import pandas as pd >>> df = pd.DataFrame( >>> np.array([[ 0.9, 0.86886931, 0.86842073, 0.9 ], >>> [ 0.34196218, 0.34289191, 0.34206377, 0.34252863], >>> [ 0.34827074, 0.34827074, 0.34827074, 0.34827074], >>> [ 0.76979453, 0.77214855, 0.77547518, 0.38850962]]), >>> columns=['sum(fgweights)', 'sum(weighted_ratio)', 'len(matches)', 'score_lnbnn_1vM'], >>> index=['match_state(match-v-rest)', 'match_state(nomatch-v-rest)', 'match_state(notcomp-v-rest)', 'photobomb_state'] >>> ) >>> highlight_cols = 'all' >>> print(to_string_monkey(df, highlight_cols)) >>> print(to_string_monkey(df, highlight_cols, latex=True)) ut.editfile(pd.io.formats.printing.adjoin) """ try: import pandas as pd import utool as ut import numpy as np import six if isinstance(highlight_cols, six.string_types) and highlight_cols == 'all': highlight_cols = np.arange(len(df.columns)) # kwds = dict(buf=None, columns=None, col_space=None, header=True, # index=True, na_rep='NaN', formatters=None, # float_format=None, sparsify=None, index_names=True, # justify=None, line_width=None, max_rows=None, # max_cols=None, show_dimensions=False) # self = pd.formats.format.DataFrameFormatter(df, **kwds) try: self = pd.formats.format.DataFrameFormatter(df) except AttributeError: self = pd.io.formats.format.DataFrameFormatter(df) self.highlight_cols = highlight_cols def monkey(self): return monkey_to_str_columns(self, latex=latex) ut.inject_func_as_method(self, monkey, '_to_str_columns', override=True, force=True) def strip_ansi(text): import re ansi_escape = re.compile(r'\x1b[^m]*m') return ansi_escape.sub('', text) def justify_ansi(self, texts, max_len, mode='right'): if mode == 'left': return [x.ljust(max_len + (len(x) - len(strip_ansi(x)))) for x in texts] elif mode == 'center': return [x.center(max_len + (len(x) - len(strip_ansi(x)))) for x in texts] else: return [x.rjust(max_len + (len(x) - len(strip_ansi(x)))) for x in texts] ut.inject_func_as_method(self.adj, justify_ansi, 'justify', override=True, force=True) def strlen_ansii(self, text): return pd.compat.strlen(strip_ansi(text), encoding=self.encoding) ut.inject_func_as_method(self.adj, strlen_ansii, 'len', override=True, force=True) if False: strlen = ut.partial(strlen_ansii, self.adj) # NOQA justfunc = ut.partial(justify_ansi, self.adj) # NOQA # Essentially what to_string does strcols = monkey_to_str_columns(self) # texts = strcols[2] space = 1 lists = strcols str_ = self.adj.adjoin(space, *lists) print(str_) print(strip_ansi(str_)) self.to_string() result = self.buf.getvalue() # hack because adjoin is not working correctly with injected strlen result = '\n'.join([x.rstrip() for x in result.split('\n')]) return result except Exception as ex: ut.printex('pandas monkey-patch is broken: {}'.format(str(ex)), tb=True, iswarning=True) return str(df)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:translate; 3, parameters; 3, 4; 4, identifier:value; 5, block; 5, 6; 5, 8; 5, 17; 5, 26; 5, 38; 5, 65; 5, 124; 5, 216; 6, expression_statement; 6, 7; 7, comment; 8, if_statement; 8, 9; 8, 14; 9, call; 9, 10; 9, 11; 10, identifier:isinstance; 11, argument_list; 11, 12; 11, 13; 12, identifier:value; 13, identifier:BaseValidator; 14, block; 14, 15; 15, return_statement; 15, 16; 16, identifier:value; 17, if_statement; 17, 18; 17, 21; 18, comparison_operator:is; 18, 19; 18, 20; 19, identifier:value; 20, None; 21, block; 21, 22; 22, return_statement; 22, 23; 23, call; 23, 24; 23, 25; 24, identifier:Anything; 25, argument_list; 26, if_statement; 26, 27; 26, 32; 27, call; 27, 28; 27, 29; 28, identifier:isinstance; 29, argument_list; 29, 30; 29, 31; 30, identifier:value; 31, identifier:type; 32, block; 32, 33; 33, return_statement; 33, 34; 34, call; 34, 35; 34, 36; 35, identifier:IsA; 36, argument_list; 36, 37; 37, identifier:value; 38, if_statement; 38, 39; 38, 47; 39, comparison_operator:in; 39, 40; 39, 44; 40, call; 40, 41; 40, 42; 41, identifier:type; 42, argument_list; 42, 43; 43, identifier:value; 44, attribute; 44, 45; 44, 46; 45, identifier:compat; 46, identifier:func_types; 47, block; 47, 48; 47, 54; 48, expression_statement; 48, 49; 49, assignment; 49, 50; 49, 51; 50, identifier:real_value; 51, call; 51, 52; 51, 53; 52, identifier:value; 53, argument_list; 54, return_statement; 54, 55; 55, call; 55, 56; 55, 57; 56, identifier:IsA; 57, argument_list; 57, 58; 57, 62; 58, call; 58, 59; 58, 60; 59, identifier:type; 60, argument_list; 60, 61; 61, identifier:real_value; 62, keyword_argument; 62, 63; 62, 64; 63, identifier:default; 64, identifier:real_value; 65, if_statement; 65, 66; 65, 71; 66, call; 66, 67; 66, 68; 67, identifier:isinstance; 68, argument_list; 68, 69; 68, 70; 69, identifier:value; 70, identifier:list; 71, block; 71, 72; 72, if_statement; 72, 73; 72, 76; 72, 77; 72, 83; 72, 102; 73, comparison_operator:==; 73, 74; 73, 75; 74, identifier:value; 75, list:[]; 76, comment; 77, block; 77, 78; 78, return_statement; 78, 79; 79, call; 79, 80; 79, 81; 80, identifier:IsA; 81, argument_list; 81, 82; 82, identifier:list; 83, elif_clause; 83, 84; 83, 90; 83, 91; 84, comparison_operator:==; 84, 85; 84, 89; 85, call; 85, 86; 85, 87; 86, identifier:len; 87, argument_list; 87, 88; 88, identifier:value; 89, integer:1; 90, comment; 91, block; 91, 92; 92, return_statement; 92, 93; 93, call; 93, 94; 93, 95; 94, identifier:ListOf; 95, argument_list; 95, 96; 96, call; 96, 97; 96, 98; 97, identifier:translate; 98, argument_list; 98, 99; 99, subscript; 99, 100; 99, 101; 100, identifier:value; 101, integer:0; 102, else_clause; 102, 103; 103, block; 103, 104; 104, raise_statement; 104, 105; 105, call; 105, 106; 105, 107; 106, identifier:StructureSpecificationError; 107, argument_list; 107, 108; 108, call; 108, 109; 108, 114; 109, attribute; 109, 110; 109, 113; 110, concatenated_string; 110, 111; 110, 112; 111, string:'Expected a list containing exactly 1 item; '; 112, string:'got {cnt}: {spec}'; 113, identifier:format; 114, argument_list; 114, 115; 114, 121; 115, keyword_argument; 115, 116; 115, 117; 116, identifier:cnt; 117, call; 117, 118; 117, 119; 118, identifier:len; 119, argument_list; 119, 120; 120, identifier:value; 121, keyword_argument; 121, 122; 121, 123; 122, identifier:spec; 123, identifier:value; 124, if_statement; 124, 125; 124, 130; 125, call; 125, 126; 125, 127; 126, identifier:isinstance; 127, argument_list; 127, 128; 127, 129; 128, identifier:value; 129, identifier:dict; 130, block; 130, 131; 130, 140; 130, 144; 130, 211; 131, if_statement; 131, 132; 131, 134; 132, not_operator; 132, 133; 133, identifier:value; 134, block; 134, 135; 135, return_statement; 135, 136; 136, call; 136, 137; 136, 138; 137, identifier:IsA; 138, argument_list; 138, 139; 139, identifier:dict; 140, expression_statement; 140, 141; 141, assignment; 141, 142; 141, 143; 142, identifier:items; 143, list:[]; 144, for_statement; 144, 145; 144, 148; 144, 153; 145, pattern_list; 145, 146; 145, 147; 146, identifier:k; 147, identifier:v; 148, call; 148, 149; 148, 152; 149, attribute; 149, 150; 149, 151; 150, identifier:value; 151, identifier:items; 152, argument_list; 153, block; 153, 154; 153, 195; 153, 202; 154, if_statement; 154, 155; 154, 160; 154, 165; 155, call; 155, 156; 155, 157; 156, identifier:isinstance; 157, argument_list; 157, 158; 157, 159; 158, identifier:k; 159, identifier:BaseValidator; 160, block; 160, 161; 161, expression_statement; 161, 162; 162, assignment; 162, 163; 162, 164; 163, identifier:k_validator; 164, identifier:k; 165, else_clause; 165, 166; 166, block; 166, 167; 166, 174; 166, 183; 167, expression_statement; 167, 168; 168, assignment; 168, 169; 168, 170; 169, identifier:k_validator; 170, call; 170, 171; 170, 172; 171, identifier:translate; 172, argument_list; 172, 173; 173, identifier:k; 174, expression_statement; 174, 175; 175, assignment; 175, 176; 175, 177; 176, identifier:default; 177, call; 177, 178; 177, 181; 178, attribute; 178, 179; 178, 180; 179, identifier:k_validator; 180, identifier:get_default_for; 181, argument_list; 181, 182; 182, None; 183, if_statement; 183, 184; 183, 187; 184, comparison_operator:is; 184, 185; 184, 186; 185, identifier:default; 186, None; 187, block; 187, 188; 188, expression_statement; 188, 189; 189, assignment; 189, 190; 189, 191; 190, identifier:k_validator; 191, call; 191, 192; 191, 193; 192, identifier:Equals; 193, argument_list; 193, 194; 194, identifier:default; 195, expression_statement; 195, 196; 196, assignment; 196, 197; 196, 198; 197, identifier:v_validator; 198, call; 198, 199; 198, 200; 199, identifier:translate; 200, argument_list; 200, 201; 201, identifier:v; 202, expression_statement; 202, 203; 203, call; 203, 204; 203, 207; 204, attribute; 204, 205; 204, 206; 205, identifier:items; 206, identifier:append; 207, argument_list; 207, 208; 208, tuple; 208, 209; 208, 210; 209, identifier:k_validator; 210, identifier:v_validator; 211, return_statement; 211, 212; 212, call; 212, 213; 212, 214; 213, identifier:DictOf; 214, argument_list; 214, 215; 215, identifier:items; 216, return_statement; 216, 217; 217, call; 217, 218; 217, 219; 218, identifier:IsA; 219, argument_list; 219, 220; 219, 224; 220, call; 220, 221; 220, 222; 221, identifier:type; 222, argument_list; 222, 223; 223, identifier:value; 224, keyword_argument; 224, 225; 224, 226; 225, identifier:default; 226, identifier:value
def translate(value): """ Translates given schema from "pythonic" syntax to a validator. Usage:: >>> translate(str) IsA(str) >>> translate('hello') IsA(str, default='hello') """ if isinstance(value, BaseValidator): return value if value is None: return Anything() if isinstance(value, type): return IsA(value) if type(value) in compat.func_types: real_value = value() return IsA(type(real_value), default=real_value) if isinstance(value, list): if value == []: # no inner spec, just an empty list as the default value return IsA(list) elif len(value) == 1: # the only item as spec for each item of the collection return ListOf(translate(value[0])) else: raise StructureSpecificationError( 'Expected a list containing exactly 1 item; ' 'got {cnt}: {spec}'.format(cnt=len(value), spec=value)) if isinstance(value, dict): if not value: return IsA(dict) items = [] for k, v in value.items(): if isinstance(k, BaseValidator): k_validator = k else: k_validator = translate(k) default = k_validator.get_default_for(None) if default is not None: k_validator = Equals(default) v_validator = translate(v) items.append((k_validator, v_validator)) return DictOf(items) return IsA(type(value), default=value)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 17; 2, function_name:parse_keys; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 3, 14; 4, identifier:string; 5, default_parameter; 5, 6; 5, 7; 6, identifier:with_spaces; 7, False; 8, default_parameter; 8, 9; 8, 10; 9, identifier:with_tabs; 10, False; 11, default_parameter; 11, 12; 11, 13; 12, identifier:with_newlines; 13, False; 14, default_parameter; 14, 15; 14, 16; 15, identifier:modifiers; 16, None; 17, block; 17, 18; 17, 20; 17, 24; 17, 32; 17, 36; 17, 338; 17, 339; 17, 359; 18, expression_statement; 18, 19; 19, string:"Return the parsed keys"; 20, expression_statement; 20, 21; 21, assignment; 21, 22; 21, 23; 22, identifier:keys; 23, list:[]; 24, if_statement; 24, 25; 24, 27; 25, not_operator; 25, 26; 26, identifier:modifiers; 27, block; 27, 28; 28, expression_statement; 28, 29; 29, assignment; 29, 30; 29, 31; 30, identifier:modifiers; 31, list:[]; 32, expression_statement; 32, 33; 33, assignment; 33, 34; 33, 35; 34, identifier:index; 35, integer:0; 36, while_statement; 36, 37; 36, 43; 37, comparison_operator:<; 37, 38; 37, 39; 38, identifier:index; 39, call; 39, 40; 39, 41; 40, identifier:len; 41, argument_list; 41, 42; 42, identifier:string; 43, block; 43, 44; 43, 50; 43, 54; 43, 55; 43, 308; 43, 309; 44, expression_statement; 44, 45; 45, assignment; 45, 46; 45, 47; 46, identifier:c; 47, subscript; 47, 48; 47, 49; 48, identifier:string; 49, identifier:index; 50, expression_statement; 50, 51; 51, augmented_assignment:+=; 51, 52; 51, 53; 52, identifier:index; 53, integer:1; 54, comment; 55, if_statement; 55, 56; 55, 63; 55, 102; 55, 103; 55, 154; 55, 155; 55, 209; 55, 210; 55, 220; 55, 221; 55, 231; 55, 232; 56, comparison_operator:in; 56, 57; 56, 58; 57, identifier:c; 58, call; 58, 59; 58, 62; 59, attribute; 59, 60; 59, 61; 60, identifier:MODIFIERS; 61, identifier:keys; 62, argument_list; 63, block; 63, 64; 63, 70; 63, 71; 63, 78; 63, 79; 63, 92; 63, 101; 64, expression_statement; 64, 65; 65, assignment; 65, 66; 65, 67; 66, identifier:modifier; 67, subscript; 67, 68; 67, 69; 68, identifier:MODIFIERS; 69, identifier:c; 70, comment; 71, expression_statement; 71, 72; 72, call; 72, 73; 72, 76; 73, attribute; 73, 74; 73, 75; 74, identifier:modifiers; 75, identifier:append; 76, argument_list; 76, 77; 77, identifier:modifier; 78, comment; 79, expression_statement; 79, 80; 80, call; 80, 81; 80, 84; 81, attribute; 81, 82; 81, 83; 82, identifier:keys; 83, identifier:append; 84, argument_list; 84, 85; 85, call; 85, 86; 85, 87; 86, identifier:VirtualKeyAction; 87, argument_list; 87, 88; 87, 89; 88, identifier:modifier; 89, keyword_argument; 89, 90; 89, 91; 90, identifier:up; 91, False; 92, if_statement; 92, 93; 92, 94; 93, identifier:DEBUG; 94, block; 94, 95; 95, expression_statement; 95, 96; 96, call; 96, 97; 96, 98; 97, identifier:print; 98, argument_list; 98, 99; 98, 100; 99, string:"MODS+"; 100, identifier:modifiers; 101, continue_statement; 102, comment; 103, elif_clause; 103, 104; 103, 107; 103, 108; 104, comparison_operator:==; 104, 105; 104, 106; 105, identifier:c; 106, string:"("; 107, comment; 108, block; 108, 109; 108, 119; 108, 130; 108, 148; 109, expression_statement; 109, 110; 110, assignment; 110, 111; 110, 112; 111, identifier:end_pos; 112, call; 112, 113; 112, 116; 113, attribute; 113, 114; 113, 115; 114, identifier:string; 115, identifier:find; 116, argument_list; 116, 117; 116, 118; 117, string:")"; 118, identifier:index; 119, if_statement; 119, 120; 119, 124; 120, comparison_operator:==; 120, 121; 120, 122; 121, identifier:end_pos; 122, unary_operator:-; 122, 123; 123, integer:1; 124, block; 124, 125; 125, raise_statement; 125, 126; 126, call; 126, 127; 126, 128; 127, identifier:KeySequenceError; 128, argument_list; 128, 129; 129, string:'`)` not found'; 130, expression_statement; 130, 131; 131, call; 131, 132; 131, 135; 132, attribute; 132, 133; 132, 134; 133, identifier:keys; 134, identifier:extend; 135, argument_list; 135, 136; 136, call; 136, 137; 136, 138; 137, identifier:parse_keys; 138, argument_list; 138, 139; 138, 145; 139, subscript; 139, 140; 139, 141; 140, identifier:string; 141, slice; 141, 142; 141, 143; 141, 144; 142, identifier:index; 143, colon; 144, identifier:end_pos; 145, keyword_argument; 145, 146; 145, 147; 146, identifier:modifiers; 147, identifier:modifiers; 148, expression_statement; 148, 149; 149, assignment; 149, 150; 149, 151; 150, identifier:index; 151, binary_operator:+; 151, 152; 151, 153; 152, identifier:end_pos; 153, integer:1; 154, comment; 155, elif_clause; 155, 156; 155, 159; 155, 160; 156, comparison_operator:==; 156, 157; 156, 158; 157, identifier:c; 158, string:"{"; 159, comment; 160, block; 160, 161; 160, 173; 160, 184; 160, 193; 160, 199; 161, expression_statement; 161, 162; 162, assignment; 162, 163; 162, 164; 163, identifier:end_pos; 164, call; 164, 165; 164, 168; 165, attribute; 165, 166; 165, 167; 166, identifier:string; 167, identifier:find; 168, argument_list; 168, 169; 168, 170; 169, string:"}"; 170, binary_operator:+; 170, 171; 170, 172; 171, identifier:index; 172, integer:1; 173, if_statement; 173, 174; 173, 178; 174, comparison_operator:==; 174, 175; 174, 176; 175, identifier:end_pos; 176, unary_operator:-; 176, 177; 177, integer:1; 178, block; 178, 179; 179, raise_statement; 179, 180; 180, call; 180, 181; 180, 182; 181, identifier:KeySequenceError; 182, argument_list; 182, 183; 183, string:'`}` not found'; 184, expression_statement; 184, 185; 185, assignment; 185, 186; 185, 187; 186, identifier:code; 187, subscript; 187, 188; 187, 189; 188, identifier:string; 189, slice; 189, 190; 189, 191; 189, 192; 190, identifier:index; 191, colon; 192, identifier:end_pos; 193, expression_statement; 193, 194; 194, assignment; 194, 195; 194, 196; 195, identifier:index; 196, binary_operator:+; 196, 197; 196, 198; 197, identifier:end_pos; 198, integer:1; 199, expression_statement; 199, 200; 200, call; 200, 201; 200, 204; 201, attribute; 201, 202; 201, 203; 202, identifier:keys; 203, identifier:extend; 204, argument_list; 204, 205; 205, call; 205, 206; 205, 207; 206, identifier:handle_code; 207, argument_list; 207, 208; 208, identifier:code; 209, comment; 210, elif_clause; 210, 211; 210, 214; 211, comparison_operator:==; 211, 212; 211, 213; 212, identifier:c; 213, string:')'; 214, block; 214, 215; 215, raise_statement; 215, 216; 216, call; 216, 217; 216, 218; 217, identifier:KeySequenceError; 218, argument_list; 218, 219; 219, string:'`)` should be preceeded by `(`'; 220, comment; 221, elif_clause; 221, 222; 221, 225; 222, comparison_operator:==; 222, 223; 222, 224; 223, identifier:c; 224, string:'}'; 225, block; 225, 226; 226, raise_statement; 226, 227; 227, call; 227, 228; 227, 229; 228, identifier:KeySequenceError; 229, argument_list; 229, 230; 230, string:'`}` should be preceeded by `{`'; 231, comment; 232, else_clause; 232, 233; 232, 234; 233, comment; 234, block; 234, 235; 234, 259; 234, 260; 235, if_statement; 235, 236; 235, 257; 236, parenthesized_expression; 236, 237; 237, boolean_operator:or; 237, 238; 237, 251; 238, boolean_operator:or; 238, 239; 238, 245; 239, boolean_operator:and; 239, 240; 239, 243; 240, comparison_operator:==; 240, 241; 240, 242; 241, identifier:c; 242, string:' '; 243, not_operator; 243, 244; 244, identifier:with_spaces; 245, boolean_operator:and; 245, 246; 245, 249; 246, comparison_operator:==; 246, 247; 246, 248; 247, identifier:c; 248, string:'\t'; 249, not_operator; 249, 250; 250, identifier:with_tabs; 251, boolean_operator:and; 251, 252; 251, 255; 252, comparison_operator:==; 252, 253; 252, 254; 253, identifier:c; 254, string:'\n'; 255, not_operator; 255, 256; 256, identifier:with_newlines; 257, block; 257, 258; 258, continue_statement; 259, comment; 260, if_statement; 260, 261; 260, 266; 260, 279; 260, 280; 260, 281; 260, 282; 260, 283; 260, 296; 261, comparison_operator:in; 261, 262; 261, 263; 262, identifier:c; 263, tuple; 263, 264; 263, 265; 264, string:'~'; 265, string:'\n'; 266, block; 266, 267; 267, expression_statement; 267, 268; 268, call; 268, 269; 268, 272; 269, attribute; 269, 270; 269, 271; 270, identifier:keys; 271, identifier:append; 272, argument_list; 272, 273; 273, call; 273, 274; 273, 275; 274, identifier:VirtualKeyAction; 275, argument_list; 275, 276; 276, subscript; 276, 277; 276, 278; 277, identifier:CODES; 278, string:"ENTER"; 279, comment; 280, comment; 281, comment; 282, comment; 283, elif_clause; 283, 284; 283, 285; 284, identifier:modifiers; 285, block; 285, 286; 286, expression_statement; 286, 287; 287, call; 287, 288; 287, 291; 288, attribute; 288, 289; 288, 290; 289, identifier:keys; 290, identifier:append; 291, argument_list; 291, 292; 292, call; 292, 293; 292, 294; 293, identifier:EscapedKeyAction; 294, argument_list; 294, 295; 295, identifier:c; 296, else_clause; 296, 297; 297, block; 297, 298; 298, expression_statement; 298, 299; 299, call; 299, 300; 299, 303; 300, attribute; 300, 301; 300, 302; 301, identifier:keys; 302, identifier:append; 303, argument_list; 303, 304; 304, call; 304, 305; 304, 306; 305, identifier:KeyAction; 306, argument_list; 306, 307; 307, identifier:c; 308, comment; 309, while_statement; 309, 310; 309, 311; 310, identifier:modifiers; 311, block; 311, 312; 311, 321; 312, if_statement; 312, 313; 312, 314; 313, identifier:DEBUG; 314, block; 314, 315; 315, expression_statement; 315, 316; 316, call; 316, 317; 316, 318; 317, identifier:print; 318, argument_list; 318, 319; 318, 320; 319, string:"MODS-"; 320, identifier:modifiers; 321, expression_statement; 321, 322; 322, call; 322, 323; 322, 326; 323, attribute; 323, 324; 323, 325; 324, identifier:keys; 325, identifier:append; 326, argument_list; 326, 327; 327, call; 327, 328; 327, 329; 328, identifier:VirtualKeyAction; 329, argument_list; 329, 330; 329, 335; 330, call; 330, 331; 330, 334; 331, attribute; 331, 332; 331, 333; 332, identifier:modifiers; 333, identifier:pop; 334, argument_list; 335, keyword_argument; 335, 336; 335, 337; 336, identifier:down; 337, False; 338, comment; 339, while_statement; 339, 340; 339, 341; 340, identifier:modifiers; 341, block; 341, 342; 342, expression_statement; 342, 343; 343, call; 343, 344; 343, 347; 344, attribute; 344, 345; 344, 346; 345, identifier:keys; 346, identifier:append; 347, argument_list; 347, 348; 348, call; 348, 349; 348, 350; 349, identifier:VirtualKeyAction; 350, argument_list; 350, 351; 350, 356; 351, call; 351, 352; 351, 355; 352, attribute; 352, 353; 352, 354; 353, identifier:modifiers; 354, identifier:pop; 355, argument_list; 356, keyword_argument; 356, 357; 356, 358; 357, identifier:down; 358, False; 359, return_statement; 359, 360; 360, identifier:keys
def parse_keys(string, with_spaces = False, with_tabs = False, with_newlines = False, modifiers = None): "Return the parsed keys" keys = [] if not modifiers: modifiers = [] index = 0 while index < len(string): c = string[index] index += 1 # check if one of CTRL, SHIFT, ALT has been pressed if c in MODIFIERS.keys(): modifier = MODIFIERS[c] # remember that we are currently modified modifiers.append(modifier) # hold down the modifier key keys.append(VirtualKeyAction(modifier, up = False)) if DEBUG: print("MODS+", modifiers) continue # Apply modifiers over a bunch of characters (not just one!) elif c == "(": # find the end of the bracketed text end_pos = string.find(")", index) if end_pos == -1: raise KeySequenceError('`)` not found') keys.extend( parse_keys(string[index:end_pos], modifiers = modifiers)) index = end_pos + 1 # Escape or named key elif c == "{": # We start searching from index + 1 to account for the case {}} end_pos = string.find("}", index + 1) if end_pos == -1: raise KeySequenceError('`}` not found') code = string[index:end_pos] index = end_pos + 1 keys.extend(handle_code(code)) # unmatched ")" elif c == ')': raise KeySequenceError('`)` should be preceeded by `(`') # unmatched "}" elif c == '}': raise KeySequenceError('`}` should be preceeded by `{`') # so it is a normal character else: # don't output white space unless flags to output have been set if (c == ' ' and not with_spaces or c == '\t' and not with_tabs or c == '\n' and not with_newlines): continue # output nuewline if c in ('~', '\n'): keys.append(VirtualKeyAction(CODES["ENTER"])) # safest are the virtual keys - so if our key is a virtual key # use a VirtualKeyAction #if ord(c) in CODE_NAMES: # keys.append(VirtualKeyAction(ord(c))) elif modifiers: keys.append(EscapedKeyAction(c)) else: keys.append(KeyAction(c)) # as we have handled the text - release the modifiers while modifiers: if DEBUG: print("MODS-", modifiers) keys.append(VirtualKeyAction(modifiers.pop(), down = False)) # just in case there were any modifiers left pressed - release them while modifiers: keys.append(VirtualKeyAction(modifiers.pop(), down = False)) return keys
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 28; 2, function_name:get_argflag; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 3, 14; 3, 17; 3, 20; 3, 23; 3, 26; 4, identifier:argstr_; 5, default_parameter; 5, 6; 5, 7; 6, identifier:default; 7, False; 8, default_parameter; 8, 9; 8, 10; 9, identifier:help_; 10, string:''; 11, default_parameter; 11, 12; 11, 13; 12, identifier:return_specified; 13, None; 14, default_parameter; 14, 15; 14, 16; 15, identifier:need_prefix; 16, True; 17, default_parameter; 17, 18; 17, 19; 18, identifier:return_was_specified; 19, False; 20, default_parameter; 20, 21; 20, 22; 21, identifier:argv; 22, None; 23, default_parameter; 23, 24; 23, 25; 24, identifier:debug; 25, None; 26, dictionary_splat_pattern; 26, 27; 27, identifier:kwargs; 28, block; 28, 29; 28, 31; 28, 42; 28, 49; 28, 58; 28, 59; 28, 60; 28, 61; 28, 69; 28, 73; 28, 77; 28, 86; 28, 87; 28, 90; 28, 91; 28, 92; 28, 93; 28, 94; 28, 95; 28, 96; 28, 209; 28, 356; 28, 365; 29, expression_statement; 29, 30; 30, comment; 31, if_statement; 31, 32; 31, 35; 32, comparison_operator:is; 32, 33; 32, 34; 33, identifier:argv; 34, None; 35, block; 35, 36; 36, expression_statement; 36, 37; 37, assignment; 37, 38; 37, 39; 38, identifier:argv; 39, attribute; 39, 40; 39, 41; 40, identifier:sys; 41, identifier:argv; 42, assert_statement; 42, 43; 42, 48; 43, call; 43, 44; 43, 45; 44, identifier:isinstance; 45, argument_list; 45, 46; 45, 47; 46, identifier:default; 47, identifier:bool; 48, string:'default must be boolean'; 49, expression_statement; 49, 50; 50, assignment; 50, 51; 50, 52; 51, identifier:argstr_list; 52, call; 52, 53; 52, 56; 53, attribute; 53, 54; 53, 55; 54, identifier:meta_util_iter; 55, identifier:ensure_iterable; 56, argument_list; 56, 57; 57, identifier:argstr_; 58, comment; 59, comment; 60, comment; 61, expression_statement; 61, 62; 62, call; 62, 63; 62, 64; 63, identifier:_register_arg; 64, argument_list; 64, 65; 64, 66; 64, 67; 64, 68; 65, identifier:argstr_list; 66, identifier:bool; 67, identifier:default; 68, identifier:help_; 69, expression_statement; 69, 70; 70, assignment; 70, 71; 70, 72; 71, identifier:parsed_val; 72, identifier:default; 73, expression_statement; 73, 74; 74, assignment; 74, 75; 74, 76; 75, identifier:was_specified; 76, False; 77, if_statement; 77, 78; 77, 81; 78, comparison_operator:is; 78, 79; 78, 80; 79, identifier:debug; 80, None; 81, block; 81, 82; 82, expression_statement; 82, 83; 83, assignment; 83, 84; 83, 85; 84, identifier:debug; 85, identifier:DEBUG; 86, comment; 87, import_statement; 87, 88; 88, dotted_name; 88, 89; 89, identifier:os; 90, comment; 91, comment; 92, comment; 93, comment; 94, comment; 95, comment; 96, for_statement; 96, 97; 96, 100; 96, 107; 97, pattern_list; 97, 98; 97, 99; 98, identifier:key; 99, identifier:val; 100, call; 100, 101; 100, 106; 101, attribute; 101, 102; 101, 105; 102, attribute; 102, 103; 102, 104; 103, identifier:os; 104, identifier:environ; 105, identifier:items; 106, argument_list; 107, block; 107, 108; 107, 116; 107, 120; 108, expression_statement; 108, 109; 109, assignment; 109, 110; 109, 111; 110, identifier:key; 111, call; 111, 112; 111, 115; 112, attribute; 112, 113; 112, 114; 113, identifier:key; 114, identifier:upper; 115, argument_list; 116, expression_statement; 116, 117; 117, assignment; 117, 118; 117, 119; 118, identifier:sentinal; 119, string:'UTOOL_'; 120, if_statement; 120, 121; 120, 127; 121, call; 121, 122; 121, 125; 122, attribute; 122, 123; 122, 124; 123, identifier:key; 124, identifier:startswith; 125, argument_list; 125, 126; 126, identifier:sentinal; 127, block; 127, 128; 127, 151; 127, 179; 127, 184; 127, 193; 128, expression_statement; 128, 129; 129, assignment; 129, 130; 129, 131; 130, identifier:flag; 131, binary_operator:+; 131, 132; 131, 133; 132, string:'--'; 133, call; 133, 134; 133, 148; 134, attribute; 134, 135; 134, 147; 135, call; 135, 136; 135, 146; 136, attribute; 136, 137; 136, 145; 137, subscript; 137, 138; 137, 139; 138, identifier:key; 139, slice; 139, 140; 139, 144; 140, call; 140, 141; 140, 142; 141, identifier:len; 142, argument_list; 142, 143; 143, identifier:sentinal; 144, colon; 145, identifier:lower; 146, argument_list; 147, identifier:replace; 148, argument_list; 148, 149; 148, 150; 149, string:'_'; 150, string:'-'; 151, if_statement; 151, 152; 151, 161; 151, 163; 151, 175; 152, comparison_operator:in; 152, 153; 152, 158; 153, call; 153, 154; 153, 157; 154, attribute; 154, 155; 154, 156; 155, identifier:val; 156, identifier:upper; 157, argument_list; 158, list:['TRUE', 'ON']; 158, 159; 158, 160; 159, string:'TRUE'; 160, string:'ON'; 161, block; 161, 162; 162, pass_statement; 163, elif_clause; 163, 164; 163, 173; 164, comparison_operator:in; 164, 165; 164, 170; 165, call; 165, 166; 165, 169; 166, attribute; 166, 167; 166, 168; 167, identifier:val; 168, identifier:upper; 169, argument_list; 170, list:['FALSE', 'OFF']; 170, 171; 170, 172; 171, string:'FALSE'; 172, string:'OFF'; 173, block; 173, 174; 174, continue_statement; 175, else_clause; 175, 176; 176, block; 176, 177; 176, 178; 177, continue_statement; 178, comment; 179, expression_statement; 179, 180; 180, assignment; 180, 181; 180, 182; 181, identifier:new_argv; 182, list:[flag]; 182, 183; 183, identifier:flag; 184, expression_statement; 184, 185; 185, assignment; 185, 186; 185, 187; 186, identifier:argv; 187, binary_operator:+; 187, 188; 187, 192; 188, subscript; 188, 189; 188, 190; 189, identifier:argv; 190, slice; 190, 191; 191, colon; 192, identifier:new_argv; 193, if_statement; 193, 194; 193, 195; 194, identifier:debug; 195, block; 195, 196; 195, 201; 196, expression_statement; 196, 197; 197, call; 197, 198; 197, 199; 198, identifier:print; 199, argument_list; 199, 200; 200, string:'ENV SPECIFIED COMMAND LINE'; 201, expression_statement; 201, 202; 202, call; 202, 203; 202, 204; 203, identifier:print; 204, argument_list; 204, 205; 205, binary_operator:%; 205, 206; 205, 207; 206, string:'argv.extend(new_argv=%r)'; 207, tuple; 207, 208; 208, identifier:new_argv; 209, for_statement; 209, 210; 209, 211; 209, 212; 209, 213; 209, 214; 210, identifier:argstr; 211, identifier:argstr_list; 212, comment; 213, comment; 214, block; 214, 215; 214, 252; 214, 280; 214, 281; 214, 282; 214, 292; 215, if_statement; 215, 216; 215, 243; 216, not_operator; 216, 217; 217, parenthesized_expression; 217, 218; 218, boolean_operator:or; 218, 219; 218, 227; 219, comparison_operator:==; 219, 220; 219, 226; 220, call; 220, 221; 220, 224; 221, attribute; 221, 222; 221, 223; 222, identifier:argstr; 223, identifier:find; 224, argument_list; 224, 225; 225, string:'--'; 226, integer:0; 227, parenthesized_expression; 227, 228; 228, boolean_operator:and; 228, 229; 228, 237; 229, comparison_operator:==; 229, 230; 229, 236; 230, call; 230, 231; 230, 234; 231, attribute; 231, 232; 231, 233; 232, identifier:argstr; 233, identifier:find; 234, argument_list; 234, 235; 235, string:'-'; 236, integer:0; 237, comparison_operator:==; 237, 238; 237, 242; 238, call; 238, 239; 238, 240; 239, identifier:len; 240, argument_list; 240, 241; 241, identifier:argstr; 242, integer:2; 243, block; 243, 244; 244, raise_statement; 244, 245; 245, call; 245, 246; 245, 247; 246, identifier:AssertionError; 247, argument_list; 247, 248; 248, binary_operator:%; 248, 249; 248, 250; 249, string:'Invalid argstr: %r'; 250, tuple; 250, 251; 251, identifier:argstr; 252, if_statement; 252, 253; 252, 255; 253, not_operator; 253, 254; 254, identifier:need_prefix; 255, block; 255, 256; 255, 266; 256, expression_statement; 256, 257; 257, assignment; 257, 258; 257, 259; 258, identifier:noprefix; 259, call; 259, 260; 259, 263; 260, attribute; 260, 261; 260, 262; 261, identifier:argstr; 262, identifier:replace; 263, argument_list; 263, 264; 263, 265; 264, string:'--'; 265, string:''; 266, if_statement; 266, 267; 266, 270; 267, comparison_operator:in; 267, 268; 267, 269; 268, identifier:noprefix; 269, identifier:argv; 270, block; 270, 271; 270, 275; 270, 279; 271, expression_statement; 271, 272; 272, assignment; 272, 273; 272, 274; 273, identifier:parsed_val; 274, True; 275, expression_statement; 275, 276; 276, assignment; 276, 277; 276, 278; 277, identifier:was_specified; 278, True; 279, break_statement; 280, comment; 281, comment; 282, expression_statement; 282, 283; 283, assignment; 283, 284; 283, 285; 284, identifier:noarg; 285, call; 285, 286; 285, 289; 286, attribute; 286, 287; 286, 288; 287, identifier:argstr; 288, identifier:replace; 289, argument_list; 289, 290; 289, 291; 290, string:'--'; 291, string:'--no'; 292, if_statement; 292, 293; 292, 296; 292, 308; 292, 324; 292, 340; 293, comparison_operator:in; 293, 294; 293, 295; 294, identifier:argstr; 295, identifier:argv; 296, block; 296, 297; 296, 301; 296, 305; 296, 306; 296, 307; 297, expression_statement; 297, 298; 298, assignment; 298, 299; 298, 300; 299, identifier:parsed_val; 300, True; 301, expression_statement; 301, 302; 302, assignment; 302, 303; 302, 304; 303, identifier:was_specified; 304, True; 305, comment; 306, comment; 307, break_statement; 308, elif_clause; 308, 309; 308, 312; 309, comparison_operator:in; 309, 310; 309, 311; 310, identifier:noarg; 311, identifier:argv; 312, block; 312, 313; 312, 317; 312, 321; 312, 322; 312, 323; 313, expression_statement; 313, 314; 314, assignment; 314, 315; 314, 316; 315, identifier:parsed_val; 316, False; 317, expression_statement; 317, 318; 318, assignment; 318, 319; 318, 320; 319, identifier:was_specified; 320, True; 321, comment; 322, comment; 323, break_statement; 324, elif_clause; 324, 325; 324, 330; 325, comparison_operator:in; 325, 326; 325, 329; 326, binary_operator:+; 326, 327; 326, 328; 327, identifier:argstr; 328, string:'=True'; 329, identifier:argv; 330, block; 330, 331; 330, 335; 330, 339; 331, expression_statement; 331, 332; 332, assignment; 332, 333; 332, 334; 333, identifier:parsed_val; 334, True; 335, expression_statement; 335, 336; 336, assignment; 336, 337; 336, 338; 337, identifier:was_specified; 338, True; 339, break_statement; 340, elif_clause; 340, 341; 340, 346; 341, comparison_operator:in; 341, 342; 341, 345; 342, binary_operator:+; 342, 343; 342, 344; 343, identifier:argstr; 344, string:'=False'; 345, identifier:argv; 346, block; 346, 347; 346, 351; 346, 355; 347, expression_statement; 347, 348; 348, assignment; 348, 349; 348, 350; 349, identifier:parsed_val; 350, False; 351, expression_statement; 351, 352; 352, assignment; 352, 353; 352, 354; 353, identifier:was_specified; 354, True; 355, break_statement; 356, if_statement; 356, 357; 356, 360; 357, comparison_operator:is; 357, 358; 357, 359; 358, identifier:return_specified; 359, None; 360, block; 360, 361; 361, expression_statement; 361, 362; 362, assignment; 362, 363; 362, 364; 363, identifier:return_specified; 364, identifier:return_was_specified; 365, if_statement; 365, 366; 365, 367; 365, 372; 366, identifier:return_specified; 367, block; 367, 368; 368, return_statement; 368, 369; 369, expression_list; 369, 370; 369, 371; 370, identifier:parsed_val; 371, identifier:was_specified; 372, else_clause; 372, 373; 373, block; 373, 374; 374, return_statement; 374, 375; 375, identifier:parsed_val
def get_argflag(argstr_, default=False, help_='', return_specified=None, need_prefix=True, return_was_specified=False, argv=None, debug=None, **kwargs): """ Checks if the commandline has a flag or a corresponding noflag Args: argstr_ (str, list, or tuple): the flag to look for default (bool): dont use this (default = False) help_ (str): a help string (default = '') return_specified (bool): returns if flag was specified or not (default = False) Returns: tuple: (parsed_val, was_specified) TODO: depricate return_was_specified CommandLine: python -m utool.util_arg --exec-get_argflag --noface --exec-mode python -m utool.util_arg --exec-get_argflag --foo --exec-mode python -m utool.util_arg --exec-get_argflag --no-foo --exec-mode python -m utool.util_arg --exec-get_argflag --foo=True --exec-mode python -m utool.util_arg --exec-get_argflag --foo=False --exec-mode Example: >>> # DISABLE_DOCTEST >>> from utool.util_arg import * # NOQA >>> argstr_ = '--foo' >>> default = False >>> help_ = '' >>> return_specified = True >>> (parsed_val, was_specified) = get_argflag(argstr_, default, help_, return_specified) >>> result = ('(parsed_val, was_specified) = %s' % (str((parsed_val, was_specified)),)) >>> print(result) """ if argv is None: argv = sys.argv assert isinstance(default, bool), 'default must be boolean' argstr_list = meta_util_iter.ensure_iterable(argstr_) #if VERYVERBOSE: # print('[util_arg] checking argstr_list=%r' % (argstr_list,)) # arg registration _register_arg(argstr_list, bool, default, help_) parsed_val = default was_specified = False if debug is None: debug = DEBUG # Check environment variables for default as well as argv import os #""" #set UTOOL_NOCNN=True #export UTOOL_NOCNN True #""" #argv_orig = argv[:] # HACK: make this not happen very time you loop for key, val in os.environ.items(): key = key.upper() sentinal = 'UTOOL_' if key.startswith(sentinal): flag = '--' + key[len(sentinal):].lower().replace('_', '-') if val.upper() in ['TRUE', 'ON']: pass elif val.upper() in ['FALSE', 'OFF']: continue else: continue #flag += '=False' new_argv = [flag] argv = argv[:] + new_argv if debug: print('ENV SPECIFIED COMMAND LINE') print('argv.extend(new_argv=%r)' % (new_argv,)) for argstr in argstr_list: #if VERYVERBOSE: # print('[util_arg] * checking argstr=%r' % (argstr,)) if not (argstr.find('--') == 0 or (argstr.find('-') == 0 and len(argstr) == 2)): raise AssertionError('Invalid argstr: %r' % (argstr,)) if not need_prefix: noprefix = argstr.replace('--', '') if noprefix in argv: parsed_val = True was_specified = True break #if argstr.find('--no') == 0: #argstr = argstr.replace('--no', '--') noarg = argstr.replace('--', '--no') if argstr in argv: parsed_val = True was_specified = True #if VERYVERBOSE: # print('[util_arg] * ...WAS_SPECIFIED. AND PARSED') break elif noarg in argv: parsed_val = False was_specified = True #if VERYVERBOSE: # print('[util_arg] * ...WAS_SPECIFIED. AND NOT PARSED') break elif argstr + '=True' in argv: parsed_val = True was_specified = True break elif argstr + '=False' in argv: parsed_val = False was_specified = True break if return_specified is None: return_specified = return_was_specified if return_specified: return parsed_val, was_specified else: return parsed_val
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 14; 2, function_name:get_arg_dict; 3, parameters; 3, 4; 3, 7; 3, 11; 4, default_parameter; 4, 5; 4, 6; 5, identifier:argv; 6, None; 7, default_parameter; 7, 8; 7, 9; 8, identifier:prefix_list; 9, list:['--']; 9, 10; 10, string:'--'; 11, default_parameter; 11, 12; 11, 13; 12, identifier:type_hints; 13, dictionary; 14, block; 14, 15; 14, 17; 14, 28; 14, 32; 14, 51; 14, 97; 14, 168; 14, 266; 15, expression_statement; 15, 16; 16, comment; 17, if_statement; 17, 18; 17, 21; 18, comparison_operator:is; 18, 19; 18, 20; 19, identifier:argv; 20, None; 21, block; 21, 22; 22, expression_statement; 22, 23; 23, assignment; 23, 24; 23, 25; 24, identifier:argv; 25, attribute; 25, 26; 25, 27; 26, identifier:sys; 27, identifier:argv; 28, expression_statement; 28, 29; 29, assignment; 29, 30; 29, 31; 30, identifier:arg_dict; 31, dictionary; 32, function_definition; 32, 33; 32, 34; 32, 36; 33, function_name:startswith_prefix; 34, parameters; 34, 35; 35, identifier:arg; 36, block; 36, 37; 37, return_statement; 37, 38; 38, call; 38, 39; 38, 40; 39, identifier:any; 40, argument_list; 40, 41; 41, list_comprehension; 41, 42; 41, 48; 42, call; 42, 43; 42, 46; 43, attribute; 43, 44; 43, 45; 44, identifier:arg; 45, identifier:startswith; 46, argument_list; 46, 47; 47, identifier:prefix; 48, for_in_clause; 48, 49; 48, 50; 49, identifier:prefix; 50, identifier:prefix_list; 51, function_definition; 51, 52; 51, 53; 51, 56; 51, 57; 52, function_name:argx_has_value; 53, parameters; 53, 54; 53, 55; 54, identifier:argv; 55, identifier:argx; 56, comment; 57, block; 57, 58; 57, 73; 57, 95; 58, if_statement; 58, 59; 58, 70; 59, comparison_operator:>; 59, 60; 59, 68; 60, call; 60, 61; 60, 66; 61, attribute; 61, 62; 61, 65; 62, subscript; 62, 63; 62, 64; 63, identifier:argv; 64, identifier:argx; 65, identifier:find; 66, argument_list; 66, 67; 67, string:'='; 68, unary_operator:-; 68, 69; 69, integer:1; 70, block; 70, 71; 71, return_statement; 71, 72; 72, True; 73, if_statement; 73, 74; 73, 92; 74, boolean_operator:and; 74, 75; 74, 83; 75, comparison_operator:<; 75, 76; 75, 79; 76, binary_operator:+; 76, 77; 76, 78; 77, identifier:argx; 78, integer:1; 79, call; 79, 80; 79, 81; 80, identifier:len; 81, argument_list; 81, 82; 82, identifier:argv; 83, not_operator; 83, 84; 84, call; 84, 85; 84, 86; 85, identifier:startswith_prefix; 86, argument_list; 86, 87; 87, subscript; 87, 88; 87, 89; 88, identifier:argv; 89, binary_operator:+; 89, 90; 89, 91; 90, identifier:argx; 91, integer:1; 92, block; 92, 93; 93, return_statement; 93, 94; 94, True; 95, return_statement; 95, 96; 96, False; 97, function_definition; 97, 98; 97, 99; 97, 103; 98, function_name:get_arg_value; 99, parameters; 99, 100; 99, 101; 99, 102; 100, identifier:argv; 101, identifier:argx; 102, identifier:argname; 103, block; 103, 104; 104, if_statement; 104, 105; 104, 116; 104, 135; 105, comparison_operator:>; 105, 106; 105, 114; 106, call; 106, 107; 106, 112; 107, attribute; 107, 108; 107, 111; 108, subscript; 108, 109; 108, 110; 109, identifier:argv; 110, identifier:argx; 111, identifier:find; 112, argument_list; 112, 113; 113, string:'='; 114, unary_operator:-; 114, 115; 115, integer:1; 116, block; 116, 117; 117, return_statement; 117, 118; 118, call; 118, 119; 118, 122; 119, attribute; 119, 120; 119, 121; 120, string:'='; 121, identifier:join; 122, argument_list; 122, 123; 123, subscript; 123, 124; 123, 132; 124, call; 124, 125; 124, 130; 125, attribute; 125, 126; 125, 129; 126, subscript; 126, 127; 126, 128; 127, identifier:argv; 128, identifier:argx; 129, identifier:split; 130, argument_list; 130, 131; 131, string:'='; 132, slice; 132, 133; 132, 134; 133, integer:1; 134, colon; 135, else_clause; 135, 136; 136, block; 136, 137; 136, 147; 137, expression_statement; 137, 138; 138, assignment; 138, 139; 138, 140; 139, identifier:type_; 140, call; 140, 141; 140, 144; 141, attribute; 141, 142; 141, 143; 142, identifier:type_hints; 143, identifier:get; 144, argument_list; 144, 145; 144, 146; 145, identifier:argname; 146, None; 147, if_statement; 147, 148; 147, 151; 147, 158; 148, comparison_operator:is; 148, 149; 148, 150; 149, identifier:type_; 150, None; 151, block; 151, 152; 152, return_statement; 152, 153; 153, subscript; 153, 154; 153, 155; 154, identifier:argv; 155, binary_operator:+; 155, 156; 155, 157; 156, identifier:argx; 157, integer:1; 158, else_clause; 158, 159; 159, block; 159, 160; 160, return_statement; 160, 161; 161, call; 161, 162; 161, 163; 162, identifier:parse_arglist_hack; 163, argument_list; 163, 164; 163, 165; 164, identifier:argx; 165, keyword_argument; 165, 166; 165, 167; 166, identifier:argv; 167, identifier:argv; 168, for_statement; 168, 169; 168, 170; 168, 177; 169, identifier:argx; 170, call; 170, 171; 170, 172; 171, identifier:range; 172, argument_list; 172, 173; 173, call; 173, 174; 173, 175; 174, identifier:len; 175, argument_list; 175, 176; 176, identifier:argv; 177, block; 177, 178; 177, 184; 178, expression_statement; 178, 179; 179, assignment; 179, 180; 179, 181; 180, identifier:arg; 181, subscript; 181, 182; 181, 183; 182, identifier:argv; 183, identifier:argx; 184, for_statement; 184, 185; 184, 186; 184, 187; 185, identifier:prefix; 186, identifier:prefix_list; 187, block; 187, 188; 188, if_statement; 188, 189; 188, 195; 189, call; 189, 190; 189, 193; 190, attribute; 190, 191; 190, 192; 191, identifier:arg; 192, identifier:startswith; 193, argument_list; 193, 194; 194, identifier:prefix; 195, block; 195, 196; 195, 207; 195, 265; 196, expression_statement; 196, 197; 197, assignment; 197, 198; 197, 199; 198, identifier:argname; 199, subscript; 199, 200; 199, 201; 200, identifier:arg; 201, slice; 201, 202; 201, 206; 202, call; 202, 203; 202, 204; 203, identifier:len; 204, argument_list; 204, 205; 205, identifier:prefix; 206, colon; 207, if_statement; 207, 208; 207, 213; 207, 257; 208, call; 208, 209; 208, 210; 209, identifier:argx_has_value; 210, argument_list; 210, 211; 210, 212; 211, identifier:argv; 212, identifier:argx; 213, block; 213, 214; 213, 242; 213, 251; 214, if_statement; 214, 215; 214, 224; 215, comparison_operator:>; 215, 216; 215, 222; 216, call; 216, 217; 216, 220; 217, attribute; 217, 218; 217, 219; 218, identifier:arg; 219, identifier:find; 220, argument_list; 220, 221; 221, string:'='; 222, unary_operator:-; 222, 223; 223, integer:1; 224, block; 224, 225; 225, expression_statement; 225, 226; 226, assignment; 226, 227; 226, 228; 227, identifier:argname; 228, subscript; 228, 229; 228, 230; 229, identifier:arg; 230, slice; 230, 231; 230, 235; 230, 236; 231, call; 231, 232; 231, 233; 232, identifier:len; 233, argument_list; 233, 234; 234, identifier:prefix; 235, colon; 236, call; 236, 237; 236, 240; 237, attribute; 237, 238; 237, 239; 238, identifier:arg; 239, identifier:find; 240, argument_list; 240, 241; 241, string:'='; 242, expression_statement; 242, 243; 243, assignment; 243, 244; 243, 245; 244, identifier:argvalue; 245, call; 245, 246; 245, 247; 246, identifier:get_arg_value; 247, argument_list; 247, 248; 247, 249; 247, 250; 248, identifier:argv; 249, identifier:argx; 250, identifier:argname; 251, expression_statement; 251, 252; 252, assignment; 252, 253; 252, 256; 253, subscript; 253, 254; 253, 255; 254, identifier:arg_dict; 255, identifier:argname; 256, identifier:argvalue; 257, else_clause; 257, 258; 258, block; 258, 259; 259, expression_statement; 259, 260; 260, assignment; 260, 261; 260, 264; 261, subscript; 261, 262; 261, 263; 262, identifier:arg_dict; 263, identifier:argname; 264, True; 265, break_statement; 266, return_statement; 266, 267; 267, identifier:arg_dict
def get_arg_dict(argv=None, prefix_list=['--'], type_hints={}): r""" Yet another way for parsing args CommandLine: python -m utool.util_arg --exec-get_arg_dict python -m utool.util_arg --test-get_arg_dict Example: >>> # ENABLE_DOCTEST >>> from utool.util_arg import * # NOQA >>> import utool as ut >>> import shlex >>> argv = shlex.split('--test-show_name --name=IBEIS_PZ_0303 --db testdb3 --save "~/latex/crall-candidacy-2015/figures/IBEIS_PZ_0303.jpg" --dpath figures --caption="Shadowed" --figsize=11,3 --no-figtitle -t foo bar baz biz --notitle') >>> arg_dict = ut.get_arg_dict(argv, prefix_list=['--', '-'], type_hints={'t': list}) >>> result = ut.repr2(arg_dict, nl=1) >>> # verify results >>> print(result) { 'caption': 'Shadowed', 'db': 'testdb3', 'dpath': 'figures', 'figsize': '11,3', 'name': 'IBEIS_PZ_0303', 'no-figtitle': True, 'notitle': True, 'save': '~/latex/crall-candidacy-2015/figures/IBEIS_PZ_0303.jpg', 't': ['foo', 'bar', 'baz', 'biz'], 'test-show_name': True, } """ if argv is None: argv = sys.argv arg_dict = {} def startswith_prefix(arg): return any([arg.startswith(prefix) for prefix in prefix_list]) def argx_has_value(argv, argx): # Check if has a value if argv[argx].find('=') > -1: return True if argx + 1 < len(argv) and not startswith_prefix(argv[argx + 1]): return True return False def get_arg_value(argv, argx, argname): if argv[argx].find('=') > -1: return '='.join(argv[argx].split('=')[1:]) else: type_ = type_hints.get(argname, None) if type_ is None: return argv[argx + 1] else: return parse_arglist_hack(argx, argv=argv) for argx in range(len(argv)): arg = argv[argx] for prefix in prefix_list: if arg.startswith(prefix): argname = arg[len(prefix):] if argx_has_value(argv, argx): if arg.find('=') > -1: argname = arg[len(prefix):arg.find('=')] argvalue = get_arg_value(argv, argx, argname) arg_dict[argname] = argvalue else: arg_dict[argname] = True break return arg_dict
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 14; 2, function_name:__argv_flag_dec; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 4, identifier:func; 5, default_parameter; 5, 6; 5, 7; 6, identifier:default; 7, False; 8, default_parameter; 8, 9; 8, 10; 9, identifier:quiet; 10, identifier:QUIET; 11, default_parameter; 11, 12; 11, 13; 12, identifier:indent; 13, False; 14, block; 14, 15; 14, 17; 14, 22; 14, 31; 14, 49; 14, 65; 14, 266; 14, 279; 15, expression_statement; 15, 16; 16, comment; 17, import_from_statement; 17, 18; 17, 20; 18, dotted_name; 18, 19; 19, identifier:utool; 20, dotted_name; 20, 21; 21, identifier:util_decor; 22, expression_statement; 22, 23; 23, assignment; 23, 24; 23, 25; 24, identifier:flagname; 25, call; 25, 26; 25, 29; 26, attribute; 26, 27; 26, 28; 27, identifier:meta_util_six; 28, identifier:get_funcname; 29, argument_list; 29, 30; 30, identifier:func; 31, if_statement; 31, 32; 31, 40; 32, comparison_operator:==; 32, 33; 32, 39; 33, call; 33, 34; 33, 37; 34, attribute; 34, 35; 34, 36; 35, identifier:flagname; 36, identifier:find; 37, argument_list; 37, 38; 38, string:'no'; 39, integer:0; 40, block; 40, 41; 41, expression_statement; 41, 42; 42, assignment; 42, 43; 42, 44; 43, identifier:flagname; 44, subscript; 44, 45; 44, 46; 45, identifier:flagname; 46, slice; 46, 47; 46, 48; 47, integer:2; 48, colon; 49, expression_statement; 49, 50; 50, assignment; 50, 51; 50, 52; 51, identifier:flags; 52, tuple; 52, 53; 52, 62; 53, binary_operator:+; 53, 54; 53, 55; 54, string:'--'; 55, call; 55, 56; 55, 59; 56, attribute; 56, 57; 56, 58; 57, identifier:flagname; 58, identifier:replace; 59, argument_list; 59, 60; 59, 61; 60, string:'_'; 61, string:'-'; 62, binary_operator:+; 62, 63; 62, 64; 63, string:'--'; 64, identifier:flagname; 65, decorated_definition; 65, 66; 65, 75; 66, decorator; 66, 67; 67, call; 67, 68; 67, 71; 68, attribute; 68, 69; 68, 70; 69, identifier:util_decor; 70, identifier:ignores_exc_tb; 71, argument_list; 71, 72; 72, keyword_argument; 72, 73; 72, 74; 73, identifier:outer_wrapper; 74, False; 75, function_definition; 75, 76; 75, 77; 75, 82; 76, function_name:GaurdWrapper; 77, parameters; 77, 78; 77, 80; 78, list_splat_pattern; 78, 79; 79, identifier:args; 80, dictionary_splat_pattern; 80, 81; 81, identifier:kwargs; 82, block; 82, 83; 82, 88; 82, 89; 82, 99; 82, 109; 82, 135; 82, 149; 83, import_from_statement; 83, 84; 83, 86; 84, dotted_name; 84, 85; 85, identifier:utool; 86, dotted_name; 86, 87; 87, identifier:util_print; 88, comment; 89, expression_statement; 89, 90; 90, assignment; 90, 91; 90, 92; 91, identifier:default_; 92, call; 92, 93; 92, 96; 93, attribute; 93, 94; 93, 95; 94, identifier:kwargs; 95, identifier:pop; 96, argument_list; 96, 97; 96, 98; 97, string:'default'; 98, identifier:default; 99, expression_statement; 99, 100; 100, assignment; 100, 101; 100, 102; 101, identifier:alias_flags; 102, call; 102, 103; 102, 106; 103, attribute; 103, 104; 103, 105; 104, identifier:kwargs; 105, identifier:pop; 106, argument_list; 106, 107; 106, 108; 107, string:'alias_flags'; 108, list:[]; 109, expression_statement; 109, 110; 110, assignment; 110, 111; 110, 112; 111, identifier:is_flagged; 112, parenthesized_expression; 112, 113; 113, boolean_operator:or; 113, 114; 113, 124; 114, boolean_operator:or; 114, 115; 114, 120; 115, call; 115, 116; 115, 117; 116, identifier:get_argflag; 117, argument_list; 117, 118; 117, 119; 118, identifier:flags; 119, identifier:default_; 120, call; 120, 121; 120, 122; 121, identifier:get_argflag; 122, argument_list; 122, 123; 123, string:'--print-all'; 124, call; 124, 125; 124, 126; 125, identifier:any; 126, argument_list; 126, 127; 127, list_comprehension; 127, 128; 127, 132; 128, call; 128, 129; 128, 130; 129, identifier:get_argflag; 130, argument_list; 130, 131; 131, identifier:_; 132, for_in_clause; 132, 133; 132, 134; 133, identifier:_; 134, identifier:alias_flags; 135, if_statement; 135, 136; 135, 139; 136, comparison_operator:in; 136, 137; 136, 138; 137, identifier:flagname; 138, identifier:kwargs; 139, block; 139, 140; 140, expression_statement; 140, 141; 141, assignment; 141, 142; 141, 143; 142, identifier:is_flagged; 143, call; 143, 144; 143, 147; 144, attribute; 144, 145; 144, 146; 145, identifier:kwargs; 146, identifier:pop; 147, argument_list; 147, 148; 148, identifier:flagname; 149, if_statement; 149, 150; 149, 151; 149, 237; 150, identifier:is_flagged; 151, block; 151, 152; 151, 170; 151, 171; 151, 180; 151, 186; 151, 203; 151, 226; 151, 235; 152, expression_statement; 152, 153; 153, assignment; 153, 154; 153, 155; 154, identifier:func_label; 155, call; 155, 156; 155, 167; 156, attribute; 156, 157; 156, 166; 157, call; 157, 158; 157, 163; 158, attribute; 158, 159; 158, 162; 159, subscript; 159, 160; 159, 161; 160, identifier:flags; 161, integer:0; 162, identifier:replace; 163, argument_list; 163, 164; 163, 165; 164, string:'--'; 165, string:''; 166, identifier:replace; 167, argument_list; 167, 168; 167, 169; 168, string:'print-'; 169, string:''; 170, comment; 171, expression_statement; 171, 172; 172, call; 172, 173; 172, 174; 173, identifier:print; 174, argument_list; 174, 175; 175, binary_operator:+; 175, 176; 175, 179; 176, binary_operator:+; 176, 177; 176, 178; 177, string:'\n+ --- '; 178, identifier:func_label; 179, string:' ___'; 180, expression_statement; 180, 181; 181, assignment; 181, 182; 181, 183; 182, identifier:use_indent; 183, comparison_operator:is; 183, 184; 183, 185; 184, identifier:indent; 185, False; 186, if_statement; 186, 187; 186, 190; 186, 197; 187, comparison_operator:is; 187, 188; 187, 189; 188, identifier:indent; 189, True; 190, block; 190, 191; 191, expression_statement; 191, 192; 192, assignment; 192, 193; 192, 194; 193, identifier:indent_; 194, binary_operator:%; 194, 195; 194, 196; 195, string:'[%s]'; 196, identifier:func_label; 197, else_clause; 197, 198; 198, block; 198, 199; 199, expression_statement; 199, 200; 200, assignment; 200, 201; 200, 202; 201, identifier:indent_; 202, identifier:indent; 203, with_statement; 203, 204; 203, 215; 204, with_clause; 204, 205; 205, with_item; 205, 206; 206, call; 206, 207; 206, 210; 207, attribute; 207, 208; 207, 209; 208, identifier:util_print; 209, identifier:Indenter; 210, argument_list; 210, 211; 210, 212; 211, identifier:indent_; 212, keyword_argument; 212, 213; 212, 214; 213, identifier:enabled; 214, identifier:use_indent; 215, block; 215, 216; 216, expression_statement; 216, 217; 217, assignment; 217, 218; 217, 219; 218, identifier:ret; 219, call; 219, 220; 219, 221; 220, identifier:func; 221, argument_list; 221, 222; 221, 224; 222, list_splat; 222, 223; 223, identifier:args; 224, dictionary_splat; 224, 225; 225, identifier:kwargs; 226, expression_statement; 226, 227; 227, call; 227, 228; 227, 229; 228, identifier:print; 229, argument_list; 229, 230; 230, binary_operator:+; 230, 231; 230, 234; 231, binary_operator:+; 231, 232; 231, 233; 232, string:'L ___ '; 233, identifier:func_label; 234, string:'___\n'; 235, return_statement; 235, 236; 236, identifier:ret; 237, else_clause; 237, 238; 238, block; 238, 239; 238, 250; 239, expression_statement; 239, 240; 240, assignment; 240, 241; 240, 242; 241, identifier:PRINT_DISABLED_FLAGDEC; 242, not_operator; 242, 243; 243, call; 243, 244; 243, 245; 244, identifier:get_argflag; 245, argument_list; 245, 246; 245, 247; 246, string:'--noinform'; 247, keyword_argument; 247, 248; 247, 249; 248, identifier:help_; 249, string:'does not print disabled flag decorators'; 250, if_statement; 250, 251; 250, 255; 250, 256; 251, boolean_operator:and; 251, 252; 251, 254; 252, not_operator; 252, 253; 253, identifier:quiet; 254, identifier:PRINT_DISABLED_FLAGDEC; 255, comment; 256, block; 256, 257; 257, expression_statement; 257, 258; 258, call; 258, 259; 258, 260; 259, identifier:print; 260, argument_list; 260, 261; 261, binary_operator:%; 261, 262; 261, 263; 262, string:'~~~ %s ~~~'; 263, subscript; 263, 264; 263, 265; 264, identifier:flags; 265, integer:0; 266, expression_statement; 266, 267; 267, call; 267, 268; 267, 271; 268, attribute; 268, 269; 268, 270; 269, identifier:meta_util_six; 270, identifier:set_funcname; 271, argument_list; 271, 272; 271, 273; 272, identifier:GaurdWrapper; 273, call; 273, 274; 273, 277; 274, attribute; 274, 275; 274, 276; 275, identifier:meta_util_six; 276, identifier:get_funcname; 277, argument_list; 277, 278; 278, identifier:func; 279, return_statement; 279, 280; 280, identifier:GaurdWrapper
def __argv_flag_dec(func, default=False, quiet=QUIET, indent=False): """ Logic for controlling if a function gets called based on command line """ from utool import util_decor flagname = meta_util_six.get_funcname(func) if flagname.find('no') == 0: flagname = flagname[2:] flags = ( '--' + flagname.replace('_', '-'), '--' + flagname, ) @util_decor.ignores_exc_tb(outer_wrapper=False) def GaurdWrapper(*args, **kwargs): from utool import util_print # FIXME: the --print-all is a hack default_ = kwargs.pop('default', default) alias_flags = kwargs.pop('alias_flags', []) is_flagged = (get_argflag(flags, default_) or get_argflag('--print-all') or any([get_argflag(_) for _ in alias_flags])) if flagname in kwargs: is_flagged = kwargs.pop(flagname) if is_flagged: func_label = flags[0].replace('--', '').replace('print-', '') # print('') print('\n+ --- ' + func_label + ' ___') use_indent = indent is not False if indent is True: indent_ = '[%s]' % func_label else: indent_ = indent with util_print.Indenter(indent_, enabled=use_indent): ret = func(*args, **kwargs) print('L ___ ' + func_label + '___\n') return ret else: PRINT_DISABLED_FLAGDEC = not get_argflag( '--noinform', help_='does not print disabled flag decorators') if not quiet and PRINT_DISABLED_FLAGDEC: #print('\n~~~ %s ~~~' % flag) print('~~~ %s ~~~' % flags[0]) meta_util_six.set_funcname(GaurdWrapper, meta_util_six.get_funcname(func)) return GaurdWrapper
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 9; 2, function_name:include_file; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:self; 5, identifier:path; 6, default_parameter; 6, 7; 6, 8; 7, identifier:include_dirs; 8, list:[]; 9, block; 9, 10; 9, 12; 10, expression_statement; 10, 11; 11, comment; 12, if_statement; 12, 13; 12, 16; 13, attribute; 13, 14; 13, 15; 14, identifier:self; 15, identifier:include_includes; 16, block; 16, 17; 16, 29; 16, 38; 16, 49; 16, 180; 16, 186; 17, if_statement; 17, 18; 17, 21; 18, attribute; 18, 19; 18, 20; 19, identifier:self; 20, identifier:debug; 21, block; 21, 22; 22, expression_statement; 22, 23; 23, call; 23, 24; 23, 25; 24, identifier:print; 25, argument_list; 25, 26; 26, binary_operator:%; 26, 27; 26, 28; 27, string:"------------------ Including a file: %s"; 28, identifier:path; 29, expression_statement; 29, 30; 30, assignment; 30, 31; 30, 32; 31, identifier:inc_dirs; 32, conditional_expression:if; 32, 33; 32, 34; 32, 35; 33, identifier:include_dirs; 34, identifier:include_dirs; 35, attribute; 35, 36; 35, 37; 36, identifier:self; 37, identifier:include_dirs; 38, expression_statement; 38, 39; 39, assignment; 39, 40; 39, 41; 40, identifier:parser; 41, call; 41, 42; 41, 43; 42, identifier:LEMSFileParser; 43, argument_list; 43, 44; 43, 45; 43, 46; 44, identifier:self; 45, identifier:inc_dirs; 46, attribute; 46, 47; 46, 48; 47, identifier:self; 48, identifier:include_includes; 49, if_statement; 49, 50; 49, 59; 49, 107; 50, call; 50, 51; 50, 54; 51, attribute; 51, 52; 51, 53; 52, identifier:os; 53, identifier:access; 54, argument_list; 54, 55; 54, 56; 55, identifier:path; 56, attribute; 56, 57; 56, 58; 57, identifier:os; 58, identifier:F_OK; 59, block; 59, 60; 60, if_statement; 60, 61; 60, 67; 60, 92; 61, not_operator; 61, 62; 62, comparison_operator:in; 62, 63; 62, 64; 63, identifier:path; 64, attribute; 64, 65; 64, 66; 65, identifier:self; 66, identifier:included_files; 67, block; 67, 68; 67, 82; 67, 91; 68, expression_statement; 68, 69; 69, call; 69, 70; 69, 73; 70, attribute; 70, 71; 70, 72; 71, identifier:parser; 72, identifier:parse; 73, argument_list; 73, 74; 74, call; 74, 75; 74, 81; 75, attribute; 75, 76; 75, 80; 76, call; 76, 77; 76, 78; 77, identifier:open; 78, argument_list; 78, 79; 79, identifier:path; 80, identifier:read; 81, argument_list; 82, expression_statement; 82, 83; 83, call; 83, 84; 83, 89; 84, attribute; 84, 85; 84, 88; 85, attribute; 85, 86; 85, 87; 86, identifier:self; 87, identifier:included_files; 88, identifier:append; 89, argument_list; 89, 90; 90, identifier:path; 91, return_statement; 92, else_clause; 92, 93; 93, block; 93, 94; 93, 106; 94, if_statement; 94, 95; 94, 98; 95, attribute; 95, 96; 95, 97; 96, identifier:self; 97, identifier:debug; 98, block; 98, 99; 99, expression_statement; 99, 100; 100, call; 100, 101; 100, 102; 101, identifier:print; 102, argument_list; 102, 103; 103, binary_operator:%; 103, 104; 103, 105; 104, string:"Already included: %s"; 105, identifier:path; 106, return_statement; 107, else_clause; 107, 108; 108, block; 108, 109; 109, for_statement; 109, 110; 109, 111; 109, 112; 110, identifier:inc_dir; 111, identifier:inc_dirs; 112, block; 112, 113; 112, 122; 113, expression_statement; 113, 114; 114, assignment; 114, 115; 114, 116; 115, identifier:new_path; 116, parenthesized_expression; 116, 117; 117, binary_operator:+; 117, 118; 117, 121; 118, binary_operator:+; 118, 119; 118, 120; 119, identifier:inc_dir; 120, string:'/'; 121, identifier:path; 122, if_statement; 122, 123; 122, 132; 123, call; 123, 124; 123, 127; 124, attribute; 124, 125; 124, 126; 125, identifier:os; 126, identifier:access; 127, argument_list; 127, 128; 127, 129; 128, identifier:new_path; 129, attribute; 129, 130; 129, 131; 130, identifier:os; 131, identifier:F_OK; 132, block; 132, 133; 133, if_statement; 133, 134; 133, 140; 133, 165; 134, not_operator; 134, 135; 135, comparison_operator:in; 135, 136; 135, 137; 136, identifier:new_path; 137, attribute; 137, 138; 137, 139; 138, identifier:self; 139, identifier:included_files; 140, block; 140, 141; 140, 155; 140, 164; 141, expression_statement; 141, 142; 142, call; 142, 143; 142, 146; 143, attribute; 143, 144; 143, 145; 144, identifier:parser; 145, identifier:parse; 146, argument_list; 146, 147; 147, call; 147, 148; 147, 154; 148, attribute; 148, 149; 148, 153; 149, call; 149, 150; 149, 151; 150, identifier:open; 151, argument_list; 151, 152; 152, identifier:new_path; 153, identifier:read; 154, argument_list; 155, expression_statement; 155, 156; 156, call; 156, 157; 156, 162; 157, attribute; 157, 158; 157, 161; 158, attribute; 158, 159; 158, 160; 159, identifier:self; 160, identifier:included_files; 161, identifier:append; 162, argument_list; 162, 163; 163, identifier:new_path; 164, return_statement; 165, else_clause; 165, 166; 166, block; 166, 167; 166, 179; 167, if_statement; 167, 168; 167, 171; 168, attribute; 168, 169; 168, 170; 169, identifier:self; 170, identifier:debug; 171, block; 171, 172; 172, expression_statement; 172, 173; 173, call; 173, 174; 173, 175; 174, identifier:print; 175, argument_list; 175, 176; 176, binary_operator:%; 176, 177; 176, 178; 177, string:"Already included: %s"; 178, identifier:path; 179, return_statement; 180, expression_statement; 180, 181; 181, assignment; 181, 182; 181, 183; 182, identifier:msg; 183, binary_operator:+; 183, 184; 183, 185; 184, string:'Unable to open '; 185, identifier:path; 186, if_statement; 186, 187; 186, 190; 186, 196; 187, attribute; 187, 188; 187, 189; 188, identifier:self; 189, identifier:fail_on_missing_includes; 190, block; 190, 191; 191, raise_statement; 191, 192; 192, call; 192, 193; 192, 194; 193, identifier:Exception; 194, argument_list; 194, 195; 195, identifier:msg; 196, elif_clause; 196, 197; 196, 200; 197, attribute; 197, 198; 197, 199; 198, identifier:self; 199, identifier:debug; 200, block; 200, 201; 201, expression_statement; 201, 202; 202, call; 202, 203; 202, 204; 203, identifier:print; 204, argument_list; 204, 205; 205, identifier:msg
def include_file(self, path, include_dirs = []): """ Includes a file into the current model. @param path: Path to the file to be included. @type path: str @param include_dirs: Optional alternate include search path. @type include_dirs: list(str) """ if self.include_includes: if self.debug: print("------------------ Including a file: %s"%path) inc_dirs = include_dirs if include_dirs else self.include_dirs parser = LEMSFileParser(self, inc_dirs, self.include_includes) if os.access(path, os.F_OK): if not path in self.included_files: parser.parse(open(path).read()) self.included_files.append(path) return else: if self.debug: print("Already included: %s"%path) return else: for inc_dir in inc_dirs: new_path = (inc_dir + '/' + path) if os.access(new_path, os.F_OK): if not new_path in self.included_files: parser.parse(open(new_path).read()) self.included_files.append(new_path) return else: if self.debug: print("Already included: %s"%path) return msg = 'Unable to open ' + path if self.fail_on_missing_includes: raise Exception(msg) elif self.debug: print(msg)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 7; 2, function_name:resolve_simulation; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:self; 5, identifier:fc; 6, identifier:ct; 7, block; 7, 8; 7, 10; 7, 75; 7, 147; 7, 200; 7, 264; 7, 344; 8, expression_statement; 8, 9; 9, comment; 10, for_statement; 10, 11; 10, 12; 10, 17; 11, identifier:run; 12, attribute; 12, 13; 12, 16; 13, attribute; 13, 14; 13, 15; 14, identifier:ct; 15, identifier:simulation; 16, identifier:runs; 17, block; 17, 18; 17, 66; 18, try_statement; 18, 19; 18, 56; 19, block; 19, 20; 20, expression_statement; 20, 21; 21, assignment; 21, 22; 21, 23; 22, identifier:run2; 23, call; 23, 24; 23, 25; 24, identifier:Run; 25, argument_list; 25, 26; 25, 35; 25, 38; 25, 47; 26, attribute; 26, 27; 26, 34; 27, subscript; 27, 28; 27, 31; 28, attribute; 28, 29; 28, 30; 29, identifier:fc; 30, identifier:component_references; 31, attribute; 31, 32; 31, 33; 32, identifier:run; 33, identifier:component; 34, identifier:referenced_component; 35, attribute; 35, 36; 35, 37; 36, identifier:run; 37, identifier:variable; 38, attribute; 38, 39; 38, 46; 39, subscript; 39, 40; 39, 43; 40, attribute; 40, 41; 40, 42; 41, identifier:fc; 42, identifier:parameters; 43, attribute; 43, 44; 43, 45; 44, identifier:run; 45, identifier:increment; 46, identifier:numeric_value; 47, attribute; 47, 48; 47, 55; 48, subscript; 48, 49; 48, 52; 49, attribute; 49, 50; 49, 51; 50, identifier:fc; 51, identifier:parameters; 52, attribute; 52, 53; 52, 54; 53, identifier:run; 54, identifier:total; 55, identifier:numeric_value; 56, except_clause; 56, 57; 57, block; 57, 58; 58, raise_statement; 58, 59; 59, call; 59, 60; 59, 61; 60, identifier:ModelError; 61, argument_list; 61, 62; 61, 63; 62, string:"Unable to resolve simulation run parameters in component '{0}'"; 63, attribute; 63, 64; 63, 65; 64, identifier:fc; 65, identifier:id; 66, expression_statement; 66, 67; 67, call; 67, 68; 67, 73; 68, attribute; 68, 69; 68, 72; 69, attribute; 69, 70; 69, 71; 70, identifier:fc; 71, identifier:simulation; 72, identifier:add; 73, argument_list; 73, 74; 74, identifier:run2; 75, for_statement; 75, 76; 75, 77; 75, 82; 76, identifier:record; 77, attribute; 77, 78; 77, 81; 78, attribute; 78, 79; 78, 80; 79, identifier:ct; 80, identifier:simulation; 81, identifier:records; 82, block; 82, 83; 82, 138; 83, try_statement; 83, 84; 83, 128; 84, block; 84, 85; 85, expression_statement; 85, 86; 86, assignment; 86, 87; 86, 88; 87, identifier:record2; 88, call; 88, 89; 88, 90; 89, identifier:Record; 90, argument_list; 90, 91; 90, 100; 90, 114; 91, attribute; 91, 92; 91, 99; 92, subscript; 92, 93; 92, 96; 93, attribute; 93, 94; 93, 95; 94, identifier:fc; 95, identifier:paths; 96, attribute; 96, 97; 96, 98; 97, identifier:record; 98, identifier:quantity; 99, identifier:value; 100, conditional_expression:if; 100, 101; 100, 110; 100, 113; 101, attribute; 101, 102; 101, 109; 102, subscript; 102, 103; 102, 106; 103, attribute; 103, 104; 103, 105; 104, identifier:fc; 105, identifier:parameters; 106, attribute; 106, 107; 106, 108; 107, identifier:record; 108, identifier:scale; 109, identifier:numeric_value; 110, attribute; 110, 111; 110, 112; 111, identifier:record; 112, identifier:scale; 113, integer:1; 114, conditional_expression:if; 114, 115; 114, 124; 114, 127; 115, attribute; 115, 116; 115, 123; 116, subscript; 116, 117; 116, 120; 117, attribute; 117, 118; 117, 119; 118, identifier:fc; 119, identifier:texts; 120, attribute; 120, 121; 120, 122; 121, identifier:record; 122, identifier:color; 123, identifier:value; 124, attribute; 124, 125; 124, 126; 125, identifier:record; 126, identifier:color; 127, string:'#000000'; 128, except_clause; 128, 129; 129, block; 129, 130; 130, raise_statement; 130, 131; 131, call; 131, 132; 131, 133; 132, identifier:ModelError; 133, argument_list; 133, 134; 133, 135; 134, string:"Unable to resolve simulation record parameters in component '{0}'"; 135, attribute; 135, 136; 135, 137; 136, identifier:fc; 137, identifier:id; 138, expression_statement; 138, 139; 139, call; 139, 140; 139, 145; 140, attribute; 140, 141; 140, 144; 141, attribute; 141, 142; 141, 143; 142, identifier:fc; 143, identifier:simulation; 144, identifier:add; 145, argument_list; 145, 146; 146, identifier:record2; 147, for_statement; 147, 148; 147, 149; 147, 154; 148, identifier:event_record; 149, attribute; 149, 150; 149, 153; 150, attribute; 150, 151; 150, 152; 151, identifier:ct; 152, identifier:simulation; 153, identifier:event_records; 154, block; 154, 155; 154, 191; 155, try_statement; 155, 156; 155, 181; 156, block; 156, 157; 157, expression_statement; 157, 158; 158, assignment; 158, 159; 158, 160; 159, identifier:event_record2; 160, call; 160, 161; 160, 162; 161, identifier:EventRecord; 162, argument_list; 162, 163; 162, 172; 163, attribute; 163, 164; 163, 171; 164, subscript; 164, 165; 164, 168; 165, attribute; 165, 166; 165, 167; 166, identifier:fc; 167, identifier:paths; 168, attribute; 168, 169; 168, 170; 169, identifier:event_record; 170, identifier:quantity; 171, identifier:value; 172, attribute; 172, 173; 172, 180; 173, subscript; 173, 174; 173, 177; 174, attribute; 174, 175; 174, 176; 175, identifier:fc; 176, identifier:texts; 177, attribute; 177, 178; 177, 179; 178, identifier:event_record; 179, identifier:eventPort; 180, identifier:value; 181, except_clause; 181, 182; 182, block; 182, 183; 183, raise_statement; 183, 184; 184, call; 184, 185; 184, 186; 185, identifier:ModelError; 186, argument_list; 186, 187; 186, 188; 187, string:"Unable to resolve simulation event_record parameters in component '{0}'"; 188, attribute; 188, 189; 188, 190; 189, identifier:fc; 190, identifier:id; 191, expression_statement; 191, 192; 192, call; 192, 193; 192, 198; 193, attribute; 193, 194; 193, 197; 194, attribute; 194, 195; 194, 196; 195, identifier:fc; 196, identifier:simulation; 197, identifier:add; 198, argument_list; 198, 199; 199, identifier:event_record2; 200, for_statement; 200, 201; 200, 202; 200, 207; 201, identifier:dd; 202, attribute; 202, 203; 202, 206; 203, attribute; 203, 204; 203, 205; 204, identifier:ct; 205, identifier:simulation; 206, identifier:data_displays; 207, block; 207, 208; 207, 255; 208, try_statement; 208, 209; 208, 245; 209, block; 209, 210; 209, 226; 210, expression_statement; 210, 211; 211, assignment; 211, 212; 211, 213; 212, identifier:dd2; 213, call; 213, 214; 213, 215; 214, identifier:DataDisplay; 215, argument_list; 215, 216; 215, 225; 216, attribute; 216, 217; 216, 224; 217, subscript; 217, 218; 217, 221; 218, attribute; 218, 219; 218, 220; 219, identifier:fc; 220, identifier:texts; 221, attribute; 221, 222; 221, 223; 222, identifier:dd; 223, identifier:title; 224, identifier:value; 225, string:''; 226, if_statement; 226, 227; 226, 232; 227, comparison_operator:in; 227, 228; 227, 229; 228, string:'timeScale'; 229, attribute; 229, 230; 229, 231; 230, identifier:fc; 231, identifier:parameters; 232, block; 232, 233; 233, expression_statement; 233, 234; 234, assignment; 234, 235; 234, 238; 235, attribute; 235, 236; 235, 237; 236, identifier:dd2; 237, identifier:timeScale; 238, attribute; 238, 239; 238, 244; 239, subscript; 239, 240; 239, 243; 240, attribute; 240, 241; 240, 242; 241, identifier:fc; 242, identifier:parameters; 243, string:'timeScale'; 244, identifier:numeric_value; 245, except_clause; 245, 246; 246, block; 246, 247; 247, raise_statement; 247, 248; 248, call; 248, 249; 248, 250; 249, identifier:ModelError; 250, argument_list; 250, 251; 250, 252; 251, string:"Unable to resolve simulation display parameters in component '{0}'"; 252, attribute; 252, 253; 252, 254; 253, identifier:fc; 254, identifier:id; 255, expression_statement; 255, 256; 256, call; 256, 257; 256, 262; 257, attribute; 257, 258; 257, 261; 258, attribute; 258, 259; 258, 260; 259, identifier:fc; 260, identifier:simulation; 261, identifier:add; 262, argument_list; 262, 263; 263, identifier:dd2; 264, for_statement; 264, 265; 264, 266; 264, 271; 265, identifier:dw; 266, attribute; 266, 267; 266, 270; 267, attribute; 267, 268; 267, 269; 268, identifier:ct; 269, identifier:simulation; 270, identifier:data_writers; 271, block; 271, 272; 271, 335; 272, try_statement; 272, 273; 272, 325; 273, block; 273, 274; 273, 278; 273, 309; 274, expression_statement; 274, 275; 275, assignment; 275, 276; 275, 277; 276, identifier:path; 277, string:'.'; 278, if_statement; 278, 279; 278, 296; 279, boolean_operator:and; 279, 280; 279, 287; 280, subscript; 280, 281; 280, 284; 281, attribute; 281, 282; 281, 283; 282, identifier:fc; 283, identifier:texts; 284, attribute; 284, 285; 284, 286; 285, identifier:dw; 286, identifier:path; 287, attribute; 287, 288; 287, 295; 288, subscript; 288, 289; 288, 292; 289, attribute; 289, 290; 289, 291; 290, identifier:fc; 291, identifier:texts; 292, attribute; 292, 293; 292, 294; 293, identifier:dw; 294, identifier:path; 295, identifier:value; 296, block; 296, 297; 297, expression_statement; 297, 298; 298, assignment; 298, 299; 298, 300; 299, identifier:path; 300, attribute; 300, 301; 300, 308; 301, subscript; 301, 302; 301, 305; 302, attribute; 302, 303; 302, 304; 303, identifier:fc; 304, identifier:texts; 305, attribute; 305, 306; 305, 307; 306, identifier:dw; 307, identifier:path; 308, identifier:value; 309, expression_statement; 309, 310; 310, assignment; 310, 311; 310, 312; 311, identifier:dw2; 312, call; 312, 313; 312, 314; 313, identifier:DataWriter; 314, argument_list; 314, 315; 314, 316; 315, identifier:path; 316, attribute; 316, 317; 316, 324; 317, subscript; 317, 318; 317, 321; 318, attribute; 318, 319; 318, 320; 319, identifier:fc; 320, identifier:texts; 321, attribute; 321, 322; 321, 323; 322, identifier:dw; 323, identifier:file_name; 324, identifier:value; 325, except_clause; 325, 326; 326, block; 326, 327; 327, raise_statement; 327, 328; 328, call; 328, 329; 328, 330; 329, identifier:ModelError; 330, argument_list; 330, 331; 330, 332; 331, string:"Unable to resolve simulation writer parameters in component '{0}'"; 332, attribute; 332, 333; 332, 334; 333, identifier:fc; 334, identifier:id; 335, expression_statement; 335, 336; 336, call; 336, 337; 336, 342; 337, attribute; 337, 338; 337, 341; 338, attribute; 338, 339; 338, 340; 339, identifier:fc; 340, identifier:simulation; 341, identifier:add; 342, argument_list; 342, 343; 343, identifier:dw2; 344, for_statement; 344, 345; 344, 346; 344, 351; 345, identifier:ew; 346, attribute; 346, 347; 346, 350; 347, attribute; 347, 348; 347, 349; 348, identifier:ct; 349, identifier:simulation; 350, identifier:event_writers; 351, block; 351, 352; 351, 424; 352, try_statement; 352, 353; 352, 414; 353, block; 353, 354; 353, 358; 353, 389; 354, expression_statement; 354, 355; 355, assignment; 355, 356; 355, 357; 356, identifier:path; 357, string:'.'; 358, if_statement; 358, 359; 358, 376; 359, boolean_operator:and; 359, 360; 359, 367; 360, subscript; 360, 361; 360, 364; 361, attribute; 361, 362; 361, 363; 362, identifier:fc; 363, identifier:texts; 364, attribute; 364, 365; 364, 366; 365, identifier:ew; 366, identifier:path; 367, attribute; 367, 368; 367, 375; 368, subscript; 368, 369; 368, 372; 369, attribute; 369, 370; 369, 371; 370, identifier:fc; 371, identifier:texts; 372, attribute; 372, 373; 372, 374; 373, identifier:ew; 374, identifier:path; 375, identifier:value; 376, block; 376, 377; 377, expression_statement; 377, 378; 378, assignment; 378, 379; 378, 380; 379, identifier:path; 380, attribute; 380, 381; 380, 388; 381, subscript; 381, 382; 381, 385; 382, attribute; 382, 383; 382, 384; 383, identifier:fc; 384, identifier:texts; 385, attribute; 385, 386; 385, 387; 386, identifier:ew; 387, identifier:path; 388, identifier:value; 389, expression_statement; 389, 390; 390, assignment; 390, 391; 390, 392; 391, identifier:ew2; 392, call; 392, 393; 392, 394; 393, identifier:EventWriter; 394, argument_list; 394, 395; 394, 396; 394, 405; 395, identifier:path; 396, attribute; 396, 397; 396, 404; 397, subscript; 397, 398; 397, 401; 398, attribute; 398, 399; 398, 400; 399, identifier:fc; 400, identifier:texts; 401, attribute; 401, 402; 401, 403; 402, identifier:ew; 403, identifier:file_name; 404, identifier:value; 405, attribute; 405, 406; 405, 413; 406, subscript; 406, 407; 406, 410; 407, attribute; 407, 408; 407, 409; 408, identifier:fc; 409, identifier:texts; 410, attribute; 410, 411; 410, 412; 411, identifier:ew; 412, identifier:format; 413, identifier:value; 414, except_clause; 414, 415; 415, block; 415, 416; 416, raise_statement; 416, 417; 417, call; 417, 418; 417, 419; 418, identifier:ModelError; 419, argument_list; 419, 420; 419, 421; 420, string:"Unable to resolve simulation writer parameters in component '{0}'"; 421, attribute; 421, 422; 421, 423; 422, identifier:fc; 423, identifier:id; 424, expression_statement; 424, 425; 425, call; 425, 426; 425, 431; 426, attribute; 426, 427; 426, 430; 427, attribute; 427, 428; 427, 429; 428, identifier:fc; 429, identifier:simulation; 430, identifier:add; 431, argument_list; 431, 432; 432, identifier:ew2
def resolve_simulation(self, fc, ct): """ Resolve simulation specifications. """ for run in ct.simulation.runs: try: run2 = Run(fc.component_references[run.component].referenced_component, run.variable, fc.parameters[run.increment].numeric_value, fc.parameters[run.total].numeric_value) except: raise ModelError("Unable to resolve simulation run parameters in component '{0}'", fc.id) fc.simulation.add(run2) for record in ct.simulation.records: try: record2 = Record(fc.paths[record.quantity].value, fc.parameters[record.scale].numeric_value if record.scale else 1, fc.texts[record.color].value if record.color else '#000000') except: raise ModelError("Unable to resolve simulation record parameters in component '{0}'", fc.id) fc.simulation.add(record2) for event_record in ct.simulation.event_records: try: event_record2 = EventRecord(fc.paths[event_record.quantity].value, fc.texts[event_record.eventPort].value) except: raise ModelError("Unable to resolve simulation event_record parameters in component '{0}'", fc.id) fc.simulation.add(event_record2) for dd in ct.simulation.data_displays: try: dd2 = DataDisplay(fc.texts[dd.title].value, '') if 'timeScale' in fc.parameters: dd2.timeScale = fc.parameters['timeScale'].numeric_value except: raise ModelError("Unable to resolve simulation display parameters in component '{0}'", fc.id) fc.simulation.add(dd2) for dw in ct.simulation.data_writers: try: path = '.' if fc.texts[dw.path] and fc.texts[dw.path].value: path = fc.texts[dw.path].value dw2 = DataWriter(path, fc.texts[dw.file_name].value) except: raise ModelError("Unable to resolve simulation writer parameters in component '{0}'", fc.id) fc.simulation.add(dw2) for ew in ct.simulation.event_writers: try: path = '.' if fc.texts[ew.path] and fc.texts[ew.path].value: path = fc.texts[ew.path].value ew2 = EventWriter(path, fc.texts[ew.file_name].value, fc.texts[ew.format].value) except: raise ModelError("Unable to resolve simulation writer parameters in component '{0}'", fc.id) fc.simulation.add(ew2)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:order_derived_parameters; 3, parameters; 3, 4; 4, identifier:component; 5, block; 5, 6; 5, 8; 5, 20; 5, 24; 5, 28; 5, 43; 5, 47; 5, 51; 5, 127; 5, 145; 5, 146; 6, expression_statement; 6, 7; 7, comment; 8, if_statement; 8, 9; 8, 17; 9, comparison_operator:==; 9, 10; 9, 16; 10, call; 10, 11; 10, 12; 11, identifier:len; 12, argument_list; 12, 13; 13, attribute; 13, 14; 13, 15; 14, identifier:component; 15, identifier:derived_parameters; 16, integer:0; 17, block; 17, 18; 18, return_statement; 18, 19; 19, list:[]; 20, expression_statement; 20, 21; 21, assignment; 21, 22; 21, 23; 22, identifier:ordering; 23, list:[]; 24, expression_statement; 24, 25; 25, assignment; 25, 26; 25, 27; 26, identifier:dps; 27, list:[]; 28, for_statement; 28, 29; 28, 30; 28, 33; 29, identifier:dp; 30, attribute; 30, 31; 30, 32; 31, identifier:component; 32, identifier:derived_parameters; 33, block; 33, 34; 34, expression_statement; 34, 35; 35, call; 35, 36; 35, 39; 36, attribute; 36, 37; 36, 38; 37, identifier:dps; 38, identifier:append; 39, argument_list; 39, 40; 40, attribute; 40, 41; 40, 42; 41, identifier:dp; 42, identifier:name; 43, expression_statement; 43, 44; 44, assignment; 44, 45; 44, 46; 45, identifier:maxcount; 46, integer:5; 47, expression_statement; 47, 48; 48, assignment; 48, 49; 48, 50; 49, identifier:count; 50, identifier:maxcount; 51, while_statement; 51, 52; 51, 59; 52, boolean_operator:and; 52, 53; 52, 56; 53, comparison_operator:>; 53, 54; 53, 55; 54, identifier:count; 55, integer:0; 56, comparison_operator:!=; 56, 57; 56, 58; 57, identifier:dps; 58, list:[]; 59, block; 59, 60; 59, 66; 60, expression_statement; 60, 61; 61, assignment; 61, 62; 61, 63; 62, identifier:count; 63, binary_operator:-; 63, 64; 63, 65; 64, identifier:count; 65, integer:1; 66, for_statement; 66, 67; 66, 68; 66, 69; 66, 70; 67, identifier:dp1; 68, identifier:dps; 69, comment; 70, block; 70, 71; 70, 81; 70, 85; 70, 102; 71, expression_statement; 71, 72; 72, assignment; 72, 73; 72, 74; 73, identifier:value; 74, attribute; 74, 75; 74, 80; 75, subscript; 75, 76; 75, 79; 76, attribute; 76, 77; 76, 78; 77, identifier:component; 78, identifier:derived_parameters; 79, identifier:dp1; 80, identifier:value; 81, expression_statement; 81, 82; 82, assignment; 82, 83; 82, 84; 83, identifier:found; 84, False; 85, for_statement; 85, 86; 85, 87; 85, 88; 86, identifier:dp2; 87, identifier:dps; 88, block; 88, 89; 89, if_statement; 89, 90; 89, 97; 90, boolean_operator:and; 90, 91; 90, 94; 91, comparison_operator:!=; 91, 92; 91, 93; 92, identifier:dp1; 93, identifier:dp2; 94, comparison_operator:in; 94, 95; 94, 96; 95, identifier:dp2; 96, identifier:value; 97, block; 97, 98; 98, expression_statement; 98, 99; 99, assignment; 99, 100; 99, 101; 100, identifier:found; 101, True; 102, if_statement; 102, 103; 102, 105; 103, not_operator; 103, 104; 104, identifier:found; 105, block; 105, 106; 105, 113; 105, 122; 105, 126; 106, expression_statement; 106, 107; 107, call; 107, 108; 107, 111; 108, attribute; 108, 109; 108, 110; 109, identifier:ordering; 110, identifier:append; 111, argument_list; 111, 112; 112, identifier:dp1; 113, delete_statement; 113, 114; 114, subscript; 114, 115; 114, 116; 115, identifier:dps; 116, call; 116, 117; 116, 120; 117, attribute; 117, 118; 117, 119; 118, identifier:dps; 119, identifier:index; 120, argument_list; 120, 121; 121, identifier:dp1; 122, expression_statement; 122, 123; 123, assignment; 123, 124; 123, 125; 124, identifier:count; 125, identifier:maxcount; 126, break_statement; 127, if_statement; 127, 128; 127, 131; 128, comparison_operator:==; 128, 129; 128, 130; 129, identifier:count; 130, integer:0; 131, block; 131, 132; 132, raise_statement; 132, 133; 133, call; 133, 134; 133, 135; 134, identifier:SimBuildError; 135, argument_list; 135, 136; 136, call; 136, 137; 136, 143; 137, attribute; 137, 138; 137, 142; 138, parenthesized_expression; 138, 139; 139, concatenated_string; 139, 140; 139, 141; 140, string:"Unable to find ordering for derived "; 141, string:"parameter in component '{0}'"; 142, identifier:format; 143, argument_list; 143, 144; 144, identifier:component; 145, comment; 146, return_statement; 146, 147; 147, identifier:ordering
def order_derived_parameters(component): """ Finds ordering of derived_parameters. @param component: Component containing derived parameters. @type component: lems.model.component.Component @return: Returns ordered list of derived parameters. @rtype: list(string) @raise SimBuildError: Raised when a proper ordering of derived parameters could not be found. """ if len(component.derived_parameters) == 0: return [] ordering = [] dps = [] for dp in component.derived_parameters: dps.append(dp.name) maxcount = 5 count = maxcount while count > 0 and dps != []: count = count - 1 for dp1 in dps: #exp_tree = regime.derived_variables[dv1].expression_tree value = component.derived_parameters[dp1].value found = False for dp2 in dps: if dp1 != dp2 and dp2 in value: found = True if not found: ordering.append(dp1) del dps[dps.index(dp1)] count = maxcount break if count == 0: raise SimBuildError(("Unable to find ordering for derived " "parameter in component '{0}'").format(component)) #return ordering + dvsnoexp return ordering
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:order_derived_variables; 3, parameters; 3, 4; 4, identifier:regime; 5, block; 5, 6; 5, 8; 5, 12; 5, 16; 5, 20; 5, 24; 5, 57; 5, 93; 5, 97; 5, 240; 5, 260; 5, 261; 6, expression_statement; 6, 7; 7, comment; 8, expression_statement; 8, 9; 9, assignment; 9, 10; 9, 11; 10, identifier:ordering; 11, list:[]; 12, expression_statement; 12, 13; 13, assignment; 13, 14; 13, 15; 14, identifier:dvs; 15, list:[]; 16, expression_statement; 16, 17; 17, assignment; 17, 18; 17, 19; 18, identifier:dvsnoexp; 19, list:[]; 20, expression_statement; 20, 21; 21, assignment; 21, 22; 21, 23; 22, identifier:maxcount; 23, integer:5; 24, for_statement; 24, 25; 24, 26; 24, 29; 25, identifier:dv; 26, attribute; 26, 27; 26, 28; 27, identifier:regime; 28, identifier:derived_variables; 29, block; 29, 30; 30, if_statement; 30, 31; 30, 36; 30, 46; 31, comparison_operator:==; 31, 32; 31, 35; 32, attribute; 32, 33; 32, 34; 33, identifier:dv; 34, identifier:expression_tree; 35, None; 36, block; 36, 37; 37, expression_statement; 37, 38; 38, call; 38, 39; 38, 42; 39, attribute; 39, 40; 39, 41; 40, identifier:dvsnoexp; 41, identifier:append; 42, argument_list; 42, 43; 43, attribute; 43, 44; 43, 45; 44, identifier:dv; 45, identifier:name; 46, else_clause; 46, 47; 47, block; 47, 48; 48, expression_statement; 48, 49; 49, call; 49, 50; 49, 53; 50, attribute; 50, 51; 50, 52; 51, identifier:dvs; 52, identifier:append; 53, argument_list; 53, 54; 54, attribute; 54, 55; 54, 56; 55, identifier:dv; 56, identifier:name; 57, for_statement; 57, 58; 57, 59; 57, 62; 58, identifier:dv; 59, attribute; 59, 60; 59, 61; 60, identifier:regime; 61, identifier:conditional_derived_variables; 62, block; 62, 63; 63, if_statement; 63, 64; 63, 72; 63, 82; 64, comparison_operator:==; 64, 65; 64, 71; 65, call; 65, 66; 65, 67; 66, identifier:len; 67, argument_list; 67, 68; 68, attribute; 68, 69; 68, 70; 69, identifier:dv; 70, identifier:cases; 71, integer:0; 72, block; 72, 73; 73, expression_statement; 73, 74; 74, call; 74, 75; 74, 78; 75, attribute; 75, 76; 75, 77; 76, identifier:dvsnoexp; 77, identifier:append; 78, argument_list; 78, 79; 79, attribute; 79, 80; 79, 81; 80, identifier:dv; 81, identifier:name; 82, else_clause; 82, 83; 83, block; 83, 84; 84, expression_statement; 84, 85; 85, call; 85, 86; 85, 89; 86, attribute; 86, 87; 86, 88; 87, identifier:dvs; 88, identifier:append; 89, argument_list; 89, 90; 90, attribute; 90, 91; 90, 92; 91, identifier:dv; 92, identifier:name; 93, expression_statement; 93, 94; 94, assignment; 94, 95; 94, 96; 95, identifier:count; 96, identifier:maxcount; 97, while_statement; 97, 98; 97, 105; 98, boolean_operator:and; 98, 99; 98, 102; 99, comparison_operator:>; 99, 100; 99, 101; 100, identifier:count; 101, integer:0; 102, comparison_operator:!=; 102, 103; 102, 104; 103, identifier:dvs; 104, list:[]; 105, block; 105, 106; 105, 112; 106, expression_statement; 106, 107; 107, assignment; 107, 108; 107, 109; 108, identifier:count; 109, binary_operator:-; 109, 110; 109, 111; 110, identifier:count; 111, integer:1; 112, for_statement; 112, 113; 112, 114; 112, 115; 113, identifier:dv1; 114, identifier:dvs; 115, block; 115, 116; 115, 141; 115, 145; 115, 215; 116, if_statement; 116, 117; 116, 122; 116, 131; 117, comparison_operator:in; 117, 118; 117, 119; 118, identifier:dv1; 119, attribute; 119, 120; 119, 121; 120, identifier:regime; 121, identifier:derived_variables; 122, block; 122, 123; 123, expression_statement; 123, 124; 124, assignment; 124, 125; 124, 126; 125, identifier:dv; 126, subscript; 126, 127; 126, 130; 127, attribute; 127, 128; 127, 129; 128, identifier:regime; 129, identifier:derived_variables; 130, identifier:dv1; 131, else_clause; 131, 132; 132, block; 132, 133; 133, expression_statement; 133, 134; 134, assignment; 134, 135; 134, 136; 135, identifier:dv; 136, subscript; 136, 137; 136, 140; 137, attribute; 137, 138; 137, 139; 138, identifier:regime; 139, identifier:conditional_derived_variables; 140, identifier:dv1; 141, expression_statement; 141, 142; 142, assignment; 142, 143; 142, 144; 143, identifier:found; 144, False; 145, if_statement; 145, 146; 145, 151; 145, 177; 146, call; 146, 147; 146, 148; 147, identifier:isinstance; 148, argument_list; 148, 149; 148, 150; 149, identifier:dv; 150, identifier:DerivedVariable; 151, block; 151, 152; 151, 158; 152, expression_statement; 152, 153; 153, assignment; 153, 154; 153, 155; 154, identifier:exp_tree; 155, attribute; 155, 156; 155, 157; 156, identifier:dv; 157, identifier:expression_tree; 158, for_statement; 158, 159; 158, 160; 158, 161; 159, identifier:dv2; 160, identifier:dvs; 161, block; 161, 162; 162, if_statement; 162, 163; 162, 172; 163, boolean_operator:and; 163, 164; 163, 167; 164, comparison_operator:!=; 164, 165; 164, 166; 165, identifier:dv1; 166, identifier:dv2; 167, call; 167, 168; 167, 169; 168, identifier:is_var_in_exp_tree; 169, argument_list; 169, 170; 169, 171; 170, identifier:dv2; 171, identifier:exp_tree; 172, block; 172, 173; 173, expression_statement; 173, 174; 174, assignment; 174, 175; 174, 176; 175, identifier:found; 176, True; 177, else_clause; 177, 178; 178, block; 178, 179; 179, for_statement; 179, 180; 179, 181; 179, 184; 180, identifier:case; 181, attribute; 181, 182; 181, 183; 182, identifier:dv; 183, identifier:cases; 184, block; 184, 185; 185, for_statement; 185, 186; 185, 187; 185, 188; 186, identifier:dv2; 187, identifier:dvs; 188, block; 188, 189; 189, if_statement; 189, 190; 189, 210; 190, boolean_operator:and; 190, 191; 190, 194; 191, comparison_operator:!=; 191, 192; 191, 193; 192, identifier:dv1; 193, identifier:dv2; 194, parenthesized_expression; 194, 195; 195, boolean_operator:or; 195, 196; 195, 203; 196, call; 196, 197; 196, 198; 197, identifier:is_var_in_exp_tree; 198, argument_list; 198, 199; 198, 200; 199, identifier:dv2; 200, attribute; 200, 201; 200, 202; 201, identifier:case; 202, identifier:condition_expression_tree; 203, call; 203, 204; 203, 205; 204, identifier:is_var_in_exp_tree; 205, argument_list; 205, 206; 205, 207; 206, identifier:dv2; 207, attribute; 207, 208; 207, 209; 208, identifier:case; 209, identifier:value_expression_tree; 210, block; 210, 211; 211, expression_statement; 211, 212; 212, assignment; 212, 213; 212, 214; 213, identifier:found; 214, True; 215, if_statement; 215, 216; 215, 218; 216, not_operator; 216, 217; 217, identifier:found; 218, block; 218, 219; 218, 226; 218, 235; 218, 239; 219, expression_statement; 219, 220; 220, call; 220, 221; 220, 224; 221, attribute; 221, 222; 221, 223; 222, identifier:ordering; 223, identifier:append; 224, argument_list; 224, 225; 225, identifier:dv1; 226, delete_statement; 226, 227; 227, subscript; 227, 228; 227, 229; 228, identifier:dvs; 229, call; 229, 230; 229, 233; 230, attribute; 230, 231; 230, 232; 231, identifier:dvs; 232, identifier:index; 233, argument_list; 233, 234; 234, identifier:dv1; 235, expression_statement; 235, 236; 236, assignment; 236, 237; 236, 238; 237, identifier:count; 238, identifier:maxcount; 239, break_statement; 240, if_statement; 240, 241; 240, 244; 241, comparison_operator:==; 241, 242; 241, 243; 242, identifier:count; 243, integer:0; 244, block; 244, 245; 245, raise_statement; 245, 246; 246, call; 246, 247; 246, 248; 247, identifier:SimBuildError; 248, argument_list; 248, 249; 249, call; 249, 250; 249, 256; 250, attribute; 250, 251; 250, 255; 251, parenthesized_expression; 251, 252; 252, concatenated_string; 252, 253; 252, 254; 253, string:"Unable to find ordering for derived "; 254, string:"variables in regime '{0}'"; 255, identifier:format; 256, argument_list; 256, 257; 257, attribute; 257, 258; 257, 259; 258, identifier:regime; 259, identifier:name; 260, comment; 261, return_statement; 261, 262; 262, binary_operator:+; 262, 263; 262, 264; 263, identifier:dvsnoexp; 264, identifier:ordering
def order_derived_variables(regime): """ Finds ordering of derived_variables. @param regime: Dynamics Regime containing derived variables. @type regime: lems.model.dynamics.regime @return: Returns ordered list of derived variables. @rtype: list(string) @raise SimBuildError: Raised when a proper ordering of derived variables could not be found. """ ordering = [] dvs = [] dvsnoexp = [] maxcount = 5 for dv in regime.derived_variables: if dv.expression_tree == None: dvsnoexp.append(dv.name) else: dvs.append(dv.name) for dv in regime.conditional_derived_variables: if len(dv.cases) == 0: dvsnoexp.append(dv.name) else: dvs.append(dv.name) count = maxcount while count > 0 and dvs != []: count = count - 1 for dv1 in dvs: if dv1 in regime.derived_variables: dv = regime.derived_variables[dv1] else: dv = regime.conditional_derived_variables[dv1] found = False if isinstance(dv, DerivedVariable): exp_tree = dv.expression_tree for dv2 in dvs: if dv1 != dv2 and is_var_in_exp_tree(dv2, exp_tree): found = True else: for case in dv.cases: for dv2 in dvs: if dv1 != dv2 and (is_var_in_exp_tree(dv2, case.condition_expression_tree) or is_var_in_exp_tree(dv2, case.value_expression_tree)): found = True if not found: ordering.append(dv1) del dvs[dvs.index(dv1)] count = maxcount break if count == 0: raise SimBuildError(("Unable to find ordering for derived " "variables in regime '{0}'").format(regime.name)) #return ordering + dvsnoexp return dvsnoexp + ordering
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 8; 2, function_name:build_event_connections; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 7; 4, identifier:self; 5, identifier:component; 6, identifier:runnable; 7, identifier:structure; 8, block; 8, 9; 8, 11; 8, 32; 8, 33; 9, expression_statement; 9, 10; 10, comment; 11, if_statement; 11, 12; 11, 15; 12, attribute; 12, 13; 12, 14; 13, identifier:self; 14, identifier:debug; 15, block; 15, 16; 16, expression_statement; 16, 17; 17, call; 17, 18; 17, 19; 18, identifier:print; 19, argument_list; 19, 20; 20, binary_operator:%; 20, 21; 20, 22; 21, string:"\n++++++++ Calling build_event_connections of %s with runnable %s, parent %s"; 22, tuple; 22, 23; 22, 26; 22, 29; 23, attribute; 23, 24; 23, 25; 24, identifier:component; 25, identifier:id; 26, attribute; 26, 27; 26, 28; 27, identifier:runnable; 28, identifier:id; 29, attribute; 29, 30; 29, 31; 30, identifier:runnable; 31, identifier:parent; 32, comment; 33, for_statement; 33, 34; 33, 35; 33, 38; 34, identifier:ec; 35, attribute; 35, 36; 35, 37; 36, identifier:structure; 37, identifier:event_connections; 38, block; 38, 39; 38, 53; 38, 66; 38, 79; 38, 174; 38, 180; 38, 186; 38, 226; 38, 264; 38, 288; 39, if_statement; 39, 40; 39, 43; 40, attribute; 40, 41; 40, 42; 41, identifier:self; 42, identifier:debug; 43, block; 43, 44; 44, expression_statement; 44, 45; 45, call; 45, 46; 45, 47; 46, identifier:print; 47, argument_list; 47, 48; 48, call; 48, 49; 48, 52; 49, attribute; 49, 50; 49, 51; 50, identifier:ec; 51, identifier:toxml; 52, argument_list; 53, expression_statement; 53, 54; 54, assignment; 54, 55; 54, 56; 55, identifier:source; 56, call; 56, 57; 56, 62; 57, attribute; 57, 58; 57, 61; 58, attribute; 58, 59; 58, 60; 59, identifier:runnable; 60, identifier:parent; 61, identifier:resolve_path; 62, argument_list; 62, 63; 63, attribute; 63, 64; 63, 65; 64, identifier:ec; 65, identifier:from_; 66, expression_statement; 66, 67; 67, assignment; 67, 68; 67, 69; 68, identifier:target; 69, call; 69, 70; 69, 75; 70, attribute; 70, 71; 70, 74; 71, attribute; 71, 72; 71, 73; 72, identifier:runnable; 73, identifier:parent; 74, identifier:resolve_path; 75, argument_list; 75, 76; 76, attribute; 76, 77; 76, 78; 77, identifier:ec; 78, identifier:to; 79, if_statement; 79, 80; 79, 83; 79, 150; 80, attribute; 80, 81; 80, 82; 81, identifier:ec; 82, identifier:receiver; 83, block; 83, 84; 83, 96; 83, 97; 83, 105; 83, 121; 83, 136; 83, 146; 84, expression_statement; 84, 85; 85, assignment; 85, 86; 85, 87; 86, identifier:receiver_template; 87, call; 87, 88; 87, 91; 88, attribute; 88, 89; 88, 90; 89, identifier:self; 90, identifier:build_runnable; 91, argument_list; 91, 92; 91, 95; 92, attribute; 92, 93; 92, 94; 93, identifier:ec; 94, identifier:receiver; 95, identifier:target; 96, comment; 97, expression_statement; 97, 98; 98, assignment; 98, 99; 98, 100; 99, identifier:receiver; 100, call; 100, 101; 100, 104; 101, attribute; 101, 102; 101, 103; 102, identifier:receiver_template; 103, identifier:copy; 104, argument_list; 105, expression_statement; 105, 106; 106, assignment; 106, 107; 106, 110; 107, attribute; 107, 108; 107, 109; 108, identifier:receiver; 109, identifier:id; 110, call; 110, 111; 110, 114; 111, attribute; 111, 112; 111, 113; 112, string:"{0}__{1}__"; 113, identifier:format; 114, argument_list; 114, 115; 114, 118; 115, attribute; 115, 116; 115, 117; 116, identifier:component; 117, identifier:id; 118, attribute; 118, 119; 118, 120; 119, identifier:receiver_template; 120, identifier:id; 121, if_statement; 121, 122; 121, 125; 122, attribute; 122, 123; 122, 124; 123, identifier:ec; 124, identifier:receiver_container; 125, block; 125, 126; 126, expression_statement; 126, 127; 127, call; 127, 128; 127, 131; 128, attribute; 128, 129; 128, 130; 129, identifier:target; 130, identifier:add_attachment; 131, argument_list; 131, 132; 131, 133; 132, identifier:receiver; 133, attribute; 133, 134; 133, 135; 134, identifier:ec; 135, identifier:receiver_container; 136, expression_statement; 136, 137; 137, call; 137, 138; 137, 141; 138, attribute; 138, 139; 138, 140; 139, identifier:target; 140, identifier:add_child; 141, argument_list; 141, 142; 141, 145; 142, attribute; 142, 143; 142, 144; 143, identifier:receiver_template; 144, identifier:id; 145, identifier:receiver; 146, expression_statement; 146, 147; 147, assignment; 147, 148; 147, 149; 148, identifier:target; 149, identifier:receiver; 150, else_clause; 150, 151; 151, block; 151, 152; 151, 163; 152, expression_statement; 152, 153; 153, assignment; 153, 154; 153, 155; 154, identifier:source; 155, call; 155, 156; 155, 159; 156, attribute; 156, 157; 156, 158; 157, identifier:runnable; 158, identifier:resolve_path; 159, argument_list; 159, 160; 160, attribute; 160, 161; 160, 162; 161, identifier:ec; 162, identifier:from_; 163, expression_statement; 163, 164; 164, assignment; 164, 165; 164, 166; 165, identifier:target; 166, call; 166, 167; 166, 170; 167, attribute; 167, 168; 167, 169; 168, identifier:runnable; 169, identifier:resolve_path; 170, argument_list; 170, 171; 171, attribute; 171, 172; 171, 173; 172, identifier:ec; 173, identifier:to; 174, expression_statement; 174, 175; 175, assignment; 175, 176; 175, 177; 176, identifier:source_port; 177, attribute; 177, 178; 177, 179; 178, identifier:ec; 179, identifier:source_port; 180, expression_statement; 180, 181; 181, assignment; 181, 182; 181, 183; 182, identifier:target_port; 183, attribute; 183, 184; 183, 185; 184, identifier:ec; 185, identifier:target_port; 186, if_statement; 186, 187; 186, 189; 187, not_operator; 187, 188; 188, identifier:source_port; 189, block; 189, 190; 190, if_statement; 190, 191; 190, 199; 190, 208; 191, comparison_operator:==; 191, 192; 191, 198; 192, call; 192, 193; 192, 194; 193, identifier:len; 194, argument_list; 194, 195; 195, attribute; 195, 196; 195, 197; 196, identifier:source; 197, identifier:event_out_ports; 198, integer:1; 199, block; 199, 200; 200, expression_statement; 200, 201; 201, assignment; 201, 202; 201, 203; 202, identifier:source_port; 203, subscript; 203, 204; 203, 207; 204, attribute; 204, 205; 204, 206; 205, identifier:source; 206, identifier:event_out_ports; 207, integer:0; 208, else_clause; 208, 209; 209, block; 209, 210; 210, raise_statement; 210, 211; 211, call; 211, 212; 211, 213; 212, identifier:SimBuildError; 213, argument_list; 213, 214; 214, call; 214, 215; 214, 222; 215, attribute; 215, 216; 215, 221; 216, parenthesized_expression; 216, 217; 217, concatenated_string; 217, 218; 217, 219; 217, 220; 218, string:"No source event port "; 219, string:"uniquely identifiable"; 220, string:" in '{0}'"; 221, identifier:format; 222, argument_list; 222, 223; 223, attribute; 223, 224; 223, 225; 224, identifier:source; 225, identifier:id; 226, if_statement; 226, 227; 226, 229; 227, not_operator; 227, 228; 228, identifier:target_port; 229, block; 229, 230; 230, if_statement; 230, 231; 230, 239; 230, 248; 231, comparison_operator:==; 231, 232; 231, 238; 232, call; 232, 233; 232, 234; 233, identifier:len; 234, argument_list; 234, 235; 235, attribute; 235, 236; 235, 237; 236, identifier:target; 237, identifier:event_in_ports; 238, integer:1; 239, block; 239, 240; 240, expression_statement; 240, 241; 241, assignment; 241, 242; 241, 243; 242, identifier:target_port; 243, subscript; 243, 244; 243, 247; 244, attribute; 244, 245; 244, 246; 245, identifier:target; 246, identifier:event_in_ports; 247, integer:0; 248, else_clause; 248, 249; 249, block; 249, 250; 250, raise_statement; 250, 251; 251, call; 251, 252; 251, 253; 252, identifier:SimBuildError; 253, argument_list; 253, 254; 254, call; 254, 255; 254, 262; 255, attribute; 255, 256; 255, 261; 256, parenthesized_expression; 256, 257; 257, concatenated_string; 257, 258; 257, 259; 257, 260; 258, string:"No destination event port "; 259, string:"uniquely identifiable "; 260, string:"in '{0}'"; 261, identifier:format; 262, argument_list; 262, 263; 263, identifier:target; 264, if_statement; 264, 265; 264, 268; 265, attribute; 265, 266; 265, 267; 266, identifier:self; 267, identifier:debug; 268, block; 268, 269; 269, expression_statement; 269, 270; 270, call; 270, 271; 270, 272; 271, identifier:print; 272, argument_list; 272, 273; 273, binary_operator:%; 273, 274; 273, 275; 274, string:"register_event_out_callback\n Source: %s, %s (port: %s) \n -> %s, %s (port: %s)"; 275, tuple; 275, 276; 275, 277; 275, 281; 275, 282; 275, 283; 275, 287; 276, identifier:source; 277, call; 277, 278; 277, 279; 278, identifier:id; 279, argument_list; 279, 280; 280, identifier:source; 281, identifier:source_port; 282, identifier:target; 283, call; 283, 284; 283, 285; 284, identifier:id; 285, argument_list; 285, 286; 286, identifier:target; 287, identifier:target_port; 288, expression_statement; 288, 289; 289, call; 289, 290; 289, 293; 290, attribute; 290, 291; 290, 292; 291, identifier:source; 292, identifier:register_event_out_callback; 293, argument_list; 293, 294; 293, 295; 293, 296; 294, line_continuation:\; 295, identifier:source_port; 296, lambda; 296, 297; 297, call; 297, 298; 297, 301; 298, attribute; 298, 299; 298, 300; 299, identifier:target; 300, identifier:inc_event_in; 301, argument_list; 301, 302; 302, identifier:target_port
def build_event_connections(self, component, runnable, structure): """ Adds event connections to a runnable component based on the structure specifications in the component model. @param component: Component model containing structure specifications. @type component: lems.model.component.FatComponent @param runnable: Runnable component to which structure is to be added. @type runnable: lems.sim.runnable.Runnable @param structure: The structure object to be used to add structure code in the runnable component. @type structure: lems.model.structure.Structure """ if self.debug: print("\n++++++++ Calling build_event_connections of %s with runnable %s, parent %s"%(component.id, runnable.id, runnable.parent)) # Process event connections for ec in structure.event_connections: if self.debug: print(ec.toxml()) source = runnable.parent.resolve_path(ec.from_) target = runnable.parent.resolve_path(ec.to) if ec.receiver: receiver_template = self.build_runnable(ec.receiver, target) #receiver = copy.deepcopy(receiver_template) receiver = receiver_template.copy() receiver.id = "{0}__{1}__".format(component.id, receiver_template.id) if ec.receiver_container: target.add_attachment(receiver, ec.receiver_container) target.add_child(receiver_template.id, receiver) target = receiver else: source = runnable.resolve_path(ec.from_) target = runnable.resolve_path(ec.to) source_port = ec.source_port target_port = ec.target_port if not source_port: if len(source.event_out_ports) == 1: source_port = source.event_out_ports[0] else: raise SimBuildError(("No source event port " "uniquely identifiable" " in '{0}'").format(source.id)) if not target_port: if len(target.event_in_ports) == 1: target_port = target.event_in_ports[0] else: raise SimBuildError(("No destination event port " "uniquely identifiable " "in '{0}'").format(target)) if self.debug: print("register_event_out_callback\n Source: %s, %s (port: %s) \n -> %s, %s (port: %s)"%(source, id(source), source_port, target, id(target), target_port)) source.register_event_out_callback(\ source_port, lambda: target.inc_event_in(target_port))
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 11; 2, function_name:build_foreach; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, identifier:self; 5, identifier:component; 6, identifier:runnable; 7, identifier:foreach; 8, default_parameter; 8, 9; 8, 10; 9, identifier:name_mappings; 10, dictionary; 11, block; 11, 12; 11, 14; 11, 36; 11, 47; 12, expression_statement; 12, 13; 13, comment; 14, if_statement; 14, 15; 14, 18; 15, attribute; 15, 16; 15, 17; 16, identifier:self; 17, identifier:debug; 18, block; 18, 19; 19, expression_statement; 19, 20; 20, call; 20, 21; 20, 22; 21, identifier:print; 22, argument_list; 22, 23; 23, binary_operator:%; 23, 24; 23, 25; 24, string:"\n++++++++ Calling build_foreach of %s with runnable %s, parent %s, name_mappings: %s"; 25, tuple; 25, 26; 25, 29; 25, 32; 25, 35; 26, attribute; 26, 27; 26, 28; 27, identifier:component; 28, identifier:id; 29, attribute; 29, 30; 29, 31; 30, identifier:runnable; 31, identifier:id; 32, attribute; 32, 33; 32, 34; 33, identifier:runnable; 34, identifier:parent; 35, identifier:name_mappings; 36, expression_statement; 36, 37; 37, assignment; 37, 38; 37, 39; 38, identifier:target_array; 39, call; 39, 40; 39, 43; 40, attribute; 40, 41; 40, 42; 41, identifier:runnable; 42, identifier:resolve_path; 43, argument_list; 43, 44; 44, attribute; 44, 45; 44, 46; 45, identifier:foreach; 46, identifier:instances; 47, for_statement; 47, 48; 47, 49; 47, 50; 48, identifier:target_runnable; 49, identifier:target_array; 50, block; 50, 51; 50, 69; 50, 77; 50, 78; 50, 118; 50, 119; 51, if_statement; 51, 52; 51, 55; 52, attribute; 52, 53; 52, 54; 53, identifier:self; 54, identifier:debug; 55, block; 55, 56; 56, expression_statement; 56, 57; 57, call; 57, 58; 57, 59; 58, identifier:print; 59, argument_list; 59, 60; 60, binary_operator:%; 60, 61; 60, 62; 61, string:"Applying contents of for_each to %s, as %s"; 62, tuple; 62, 63; 62, 66; 63, attribute; 63, 64; 63, 65; 64, identifier:target_runnable; 65, identifier:id; 66, attribute; 66, 67; 66, 68; 67, identifier:foreach; 68, identifier:as_; 69, expression_statement; 69, 70; 70, assignment; 70, 71; 70, 76; 71, subscript; 71, 72; 71, 73; 72, identifier:name_mappings; 73, attribute; 73, 74; 73, 75; 74, identifier:foreach; 75, identifier:as_; 76, identifier:target_runnable; 77, comment; 78, for_statement; 78, 79; 78, 80; 78, 83; 78, 84; 79, identifier:fe2; 80, attribute; 80, 81; 80, 82; 81, identifier:foreach; 82, identifier:for_eachs; 83, comment; 84, block; 84, 85; 84, 96; 85, expression_statement; 85, 86; 86, assignment; 86, 87; 86, 88; 87, identifier:target_array2; 88, call; 88, 89; 88, 92; 89, attribute; 89, 90; 89, 91; 90, identifier:runnable; 91, identifier:resolve_path; 92, argument_list; 92, 93; 93, attribute; 93, 94; 93, 95; 94, identifier:fe2; 95, identifier:instances; 96, for_statement; 96, 97; 96, 98; 96, 99; 97, identifier:target_runnable2; 98, identifier:target_array2; 99, block; 99, 100; 99, 108; 100, expression_statement; 100, 101; 101, assignment; 101, 102; 101, 107; 102, subscript; 102, 103; 102, 104; 103, identifier:name_mappings; 104, attribute; 104, 105; 104, 106; 105, identifier:fe2; 106, identifier:as_; 107, identifier:target_runnable2; 108, expression_statement; 108, 109; 109, call; 109, 110; 109, 113; 110, attribute; 110, 111; 110, 112; 111, identifier:self; 112, identifier:build_foreach; 113, argument_list; 113, 114; 113, 115; 113, 116; 113, 117; 114, identifier:component; 115, identifier:runnable; 116, identifier:fe2; 117, identifier:name_mappings; 118, comment; 119, for_statement; 119, 120; 119, 121; 119, 124; 120, identifier:ec; 121, attribute; 121, 122; 121, 123; 122, identifier:foreach; 123, identifier:event_connections; 124, block; 124, 125; 124, 133; 124, 141; 124, 147; 124, 153; 124, 193; 124, 231; 124, 255; 125, expression_statement; 125, 126; 126, assignment; 126, 127; 126, 128; 127, identifier:source; 128, subscript; 128, 129; 128, 130; 129, identifier:name_mappings; 130, attribute; 130, 131; 130, 132; 131, identifier:ec; 132, identifier:from_; 133, expression_statement; 133, 134; 134, assignment; 134, 135; 134, 136; 135, identifier:target; 136, subscript; 136, 137; 136, 138; 137, identifier:name_mappings; 138, attribute; 138, 139; 138, 140; 139, identifier:ec; 140, identifier:to; 141, expression_statement; 141, 142; 142, assignment; 142, 143; 142, 144; 143, identifier:source_port; 144, attribute; 144, 145; 144, 146; 145, identifier:ec; 146, identifier:source_port; 147, expression_statement; 147, 148; 148, assignment; 148, 149; 148, 150; 149, identifier:target_port; 150, attribute; 150, 151; 150, 152; 151, identifier:ec; 152, identifier:target_port; 153, if_statement; 153, 154; 153, 156; 154, not_operator; 154, 155; 155, identifier:source_port; 156, block; 156, 157; 157, if_statement; 157, 158; 157, 166; 157, 175; 158, comparison_operator:==; 158, 159; 158, 165; 159, call; 159, 160; 159, 161; 160, identifier:len; 161, argument_list; 161, 162; 162, attribute; 162, 163; 162, 164; 163, identifier:source; 164, identifier:event_out_ports; 165, integer:1; 166, block; 166, 167; 167, expression_statement; 167, 168; 168, assignment; 168, 169; 168, 170; 169, identifier:source_port; 170, subscript; 170, 171; 170, 174; 171, attribute; 171, 172; 171, 173; 172, identifier:source; 173, identifier:event_out_ports; 174, integer:0; 175, else_clause; 175, 176; 176, block; 176, 177; 177, raise_statement; 177, 178; 178, call; 178, 179; 178, 180; 179, identifier:SimBuildError; 180, argument_list; 180, 181; 181, call; 181, 182; 181, 189; 182, attribute; 182, 183; 182, 188; 183, parenthesized_expression; 183, 184; 184, concatenated_string; 184, 185; 184, 186; 184, 187; 185, string:"No source event port "; 186, string:"uniquely identifiable"; 187, string:" in '{0}'"; 188, identifier:format; 189, argument_list; 189, 190; 190, attribute; 190, 191; 190, 192; 191, identifier:source; 192, identifier:id; 193, if_statement; 193, 194; 193, 196; 194, not_operator; 194, 195; 195, identifier:target_port; 196, block; 196, 197; 197, if_statement; 197, 198; 197, 206; 197, 215; 198, comparison_operator:==; 198, 199; 198, 205; 199, call; 199, 200; 199, 201; 200, identifier:len; 201, argument_list; 201, 202; 202, attribute; 202, 203; 202, 204; 203, identifier:target; 204, identifier:event_in_ports; 205, integer:1; 206, block; 206, 207; 207, expression_statement; 207, 208; 208, assignment; 208, 209; 208, 210; 209, identifier:target_port; 210, subscript; 210, 211; 210, 214; 211, attribute; 211, 212; 211, 213; 212, identifier:target; 213, identifier:event_in_ports; 214, integer:0; 215, else_clause; 215, 216; 216, block; 216, 217; 217, raise_statement; 217, 218; 218, call; 218, 219; 218, 220; 219, identifier:SimBuildError; 220, argument_list; 220, 221; 221, call; 221, 222; 221, 229; 222, attribute; 222, 223; 222, 228; 223, parenthesized_expression; 223, 224; 224, concatenated_string; 224, 225; 224, 226; 224, 227; 225, string:"No destination event port "; 226, string:"uniquely identifiable "; 227, string:"in '{0}'"; 228, identifier:format; 229, argument_list; 229, 230; 230, identifier:target; 231, if_statement; 231, 232; 231, 235; 232, attribute; 232, 233; 232, 234; 233, identifier:self; 234, identifier:debug; 235, block; 235, 236; 236, expression_statement; 236, 237; 237, call; 237, 238; 237, 239; 238, identifier:print; 239, argument_list; 239, 240; 240, binary_operator:%; 240, 241; 240, 242; 241, string:"register_event_out_callback\n Source: %s, %s (port: %s) \n -> %s, %s (port: %s)"; 242, tuple; 242, 243; 242, 244; 242, 248; 242, 249; 242, 250; 242, 254; 243, identifier:source; 244, call; 244, 245; 244, 246; 245, identifier:id; 246, argument_list; 246, 247; 247, identifier:source; 248, identifier:source_port; 249, identifier:target; 250, call; 250, 251; 250, 252; 251, identifier:id; 252, argument_list; 252, 253; 253, identifier:target; 254, identifier:target_port; 255, expression_statement; 255, 256; 256, call; 256, 257; 256, 260; 257, attribute; 257, 258; 257, 259; 258, identifier:source; 259, identifier:register_event_out_callback; 260, argument_list; 260, 261; 260, 262; 260, 263; 261, line_continuation:\; 262, identifier:source_port; 263, lambda; 263, 264; 264, call; 264, 265; 264, 268; 265, attribute; 265, 266; 265, 267; 266, identifier:target; 267, identifier:inc_event_in; 268, argument_list; 268, 269; 269, identifier:target_port
def build_foreach(self, component, runnable, foreach, name_mappings = {}): """ Iterate over ForEach constructs and process nested elements. @param component: Component model containing structure specifications. @type component: lems.model.component.FatComponent @param runnable: Runnable component to which structure is to be added. @type runnable: lems.sim.runnable.Runnable @param foreach: The ForEach structure object to be used to add structure code in the runnable component. @type foreach: lems.model.structure.ForEach """ if self.debug: print("\n++++++++ Calling build_foreach of %s with runnable %s, parent %s, name_mappings: %s"%(component.id, runnable.id, runnable.parent, name_mappings)) target_array = runnable.resolve_path(foreach.instances) for target_runnable in target_array: if self.debug: print("Applying contents of for_each to %s, as %s"%(target_runnable.id, foreach.as_)) name_mappings[foreach.as_] = target_runnable # Process foreach statements for fe2 in foreach.for_eachs: #print fe2.toxml() target_array2 = runnable.resolve_path(fe2.instances) for target_runnable2 in target_array2: name_mappings[fe2.as_] = target_runnable2 self.build_foreach(component, runnable, fe2, name_mappings) # Process event connections for ec in foreach.event_connections: source = name_mappings[ec.from_] target = name_mappings[ec.to] source_port = ec.source_port target_port = ec.target_port if not source_port: if len(source.event_out_ports) == 1: source_port = source.event_out_ports[0] else: raise SimBuildError(("No source event port " "uniquely identifiable" " in '{0}'").format(source.id)) if not target_port: if len(target.event_in_ports) == 1: target_port = target.event_in_ports[0] else: raise SimBuildError(("No destination event port " "uniquely identifiable " "in '{0}'").format(target)) if self.debug: print("register_event_out_callback\n Source: %s, %s (port: %s) \n -> %s, %s (port: %s)"%(source, id(source), source_port, target, id(target), target_port)) source.register_event_out_callback(\ source_port, lambda: target.inc_event_in(target_port))
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 11; 2, function_name:check_static_member_vars; 3, parameters; 3, 4; 3, 5; 3, 8; 4, identifier:class_; 5, default_parameter; 5, 6; 5, 7; 6, identifier:fpath; 7, None; 8, default_parameter; 8, 9; 8, 10; 9, identifier:only_init; 10, True; 11, block; 11, 12; 11, 14; 11, 15; 11, 16; 11, 21; 11, 95; 11, 104; 11, 107; 11, 108; 11, 117; 11, 139; 11, 182; 11, 183; 11, 184; 11, 185; 11, 186; 11, 190; 11, 227; 11, 231; 11, 235; 11, 301; 11, 310; 11, 312; 11, 313; 12, expression_statement; 12, 13; 13, comment; 14, comment; 15, comment; 16, import_statement; 16, 17; 17, aliased_import; 17, 18; 17, 20; 18, dotted_name; 18, 19; 19, identifier:utool; 20, identifier:ut; 21, if_statement; 21, 22; 21, 29; 21, 44; 22, call; 22, 23; 22, 24; 23, identifier:isinstance; 24, argument_list; 24, 25; 24, 26; 25, identifier:class_; 26, attribute; 26, 27; 26, 28; 27, identifier:six; 28, identifier:string_types; 29, block; 29, 30; 29, 34; 30, expression_statement; 30, 31; 31, assignment; 31, 32; 31, 33; 32, identifier:classname; 33, identifier:class_; 34, if_statement; 34, 35; 34, 38; 35, comparison_operator:is; 35, 36; 35, 37; 36, identifier:fpath; 37, None; 38, block; 38, 39; 39, raise_statement; 39, 40; 40, call; 40, 41; 40, 42; 41, identifier:Exception; 42, argument_list; 42, 43; 43, string:'must specify fpath'; 44, else_clause; 44, 45; 44, 46; 45, comment; 46, block; 46, 47; 46, 66; 46, 72; 47, if_statement; 47, 48; 47, 54; 47, 55; 48, not_operator; 48, 49; 49, call; 49, 50; 49, 51; 50, identifier:isinstance; 51, argument_list; 51, 52; 51, 53; 52, identifier:class_; 53, identifier:type; 54, comment; 55, block; 55, 56; 55, 60; 56, expression_statement; 56, 57; 57, assignment; 57, 58; 57, 59; 58, identifier:class_instance; 59, identifier:class_; 60, expression_statement; 60, 61; 61, assignment; 61, 62; 61, 63; 62, identifier:class_; 63, attribute; 63, 64; 63, 65; 64, identifier:class_instance; 65, identifier:__class__; 66, expression_statement; 66, 67; 67, assignment; 67, 68; 67, 69; 68, identifier:classname; 69, attribute; 69, 70; 69, 71; 70, identifier:class_; 71, identifier:__name__; 72, if_statement; 72, 73; 72, 76; 73, comparison_operator:is; 73, 74; 73, 75; 74, identifier:fpath; 75, None; 76, block; 76, 77; 76, 86; 77, expression_statement; 77, 78; 78, assignment; 78, 79; 78, 80; 79, identifier:module; 80, call; 80, 81; 80, 84; 81, attribute; 81, 82; 81, 83; 82, identifier:ut; 83, identifier:get_module_from_class; 84, argument_list; 84, 85; 85, identifier:class_; 86, expression_statement; 86, 87; 87, assignment; 87, 88; 87, 89; 88, identifier:fpath; 89, call; 89, 90; 89, 93; 90, attribute; 90, 91; 90, 92; 91, identifier:ut; 92, identifier:get_modpath; 93, argument_list; 93, 94; 94, identifier:module; 95, expression_statement; 95, 96; 96, assignment; 96, 97; 96, 98; 97, identifier:sourcecode; 98, call; 98, 99; 98, 102; 99, attribute; 99, 100; 99, 101; 100, identifier:ut; 101, identifier:readfrom; 102, argument_list; 102, 103; 103, identifier:fpath; 104, import_statement; 104, 105; 105, dotted_name; 105, 106; 106, identifier:redbaron; 107, comment; 108, expression_statement; 108, 109; 109, assignment; 109, 110; 109, 111; 110, identifier:baron; 111, call; 111, 112; 111, 115; 112, attribute; 112, 113; 112, 114; 113, identifier:redbaron; 114, identifier:RedBaron; 115, argument_list; 115, 116; 116, identifier:sourcecode; 117, for_statement; 117, 118; 117, 119; 117, 120; 118, identifier:node; 119, identifier:baron; 120, block; 120, 121; 121, if_statement; 121, 122; 121, 133; 122, boolean_operator:and; 122, 123; 122, 128; 123, comparison_operator:==; 123, 124; 123, 127; 124, attribute; 124, 125; 124, 126; 125, identifier:node; 126, identifier:type; 127, string:'class'; 128, comparison_operator:==; 128, 129; 128, 132; 129, attribute; 129, 130; 129, 131; 130, identifier:node; 131, identifier:name; 132, identifier:classname; 133, block; 133, 134; 133, 138; 134, expression_statement; 134, 135; 135, assignment; 135, 136; 135, 137; 136, identifier:classnode; 137, identifier:node; 138, break_statement; 139, function_definition; 139, 140; 139, 141; 139, 143; 140, function_name:find_parent_method; 141, parameters; 141, 142; 142, identifier:node; 143, block; 143, 144; 143, 153; 144, expression_statement; 144, 145; 145, assignment; 145, 146; 145, 147; 146, identifier:par; 147, call; 147, 148; 147, 151; 148, attribute; 148, 149; 148, 150; 149, identifier:node; 150, identifier:parent_find; 151, argument_list; 151, 152; 152, string:'def'; 153, if_statement; 153, 154; 153, 163; 154, boolean_operator:and; 154, 155; 154, 158; 155, comparison_operator:is; 155, 156; 155, 157; 156, identifier:par; 157, None; 158, comparison_operator:is; 158, 159; 158, 162; 159, attribute; 159, 160; 159, 161; 160, identifier:par; 161, identifier:parent; 162, None; 163, block; 163, 164; 164, if_statement; 164, 165; 164, 172; 164, 175; 165, comparison_operator:==; 165, 166; 165, 171; 166, attribute; 166, 167; 166, 170; 167, attribute; 167, 168; 167, 169; 168, identifier:par; 169, identifier:parent; 170, identifier:type; 171, string:'class'; 172, block; 172, 173; 173, return_statement; 173, 174; 174, identifier:par; 175, else_clause; 175, 176; 176, block; 176, 177; 177, return_statement; 177, 178; 178, call; 178, 179; 178, 180; 179, identifier:find_parent_method; 180, argument_list; 180, 181; 181, identifier:par; 182, comment; 183, comment; 184, comment; 185, comment; 186, expression_statement; 186, 187; 187, assignment; 187, 188; 187, 189; 188, identifier:class_methods; 189, list:[]; 190, for_statement; 190, 191; 190, 192; 190, 193; 191, identifier:node; 192, identifier:classnode; 193, block; 193, 194; 194, if_statement; 194, 195; 194, 200; 195, comparison_operator:==; 195, 196; 195, 199; 196, attribute; 196, 197; 196, 198; 197, identifier:node; 198, identifier:type; 199, string:'def'; 200, block; 200, 201; 201, if_statement; 201, 202; 201, 203; 201, 218; 202, identifier:only_init; 203, block; 203, 204; 204, if_statement; 204, 205; 204, 210; 205, comparison_operator:==; 205, 206; 205, 209; 206, attribute; 206, 207; 206, 208; 207, identifier:node; 208, identifier:name; 209, string:'__init__'; 210, block; 210, 211; 211, expression_statement; 211, 212; 212, call; 212, 213; 212, 216; 213, attribute; 213, 214; 213, 215; 214, identifier:class_methods; 215, identifier:append; 216, argument_list; 216, 217; 217, identifier:node; 218, else_clause; 218, 219; 219, block; 219, 220; 220, expression_statement; 220, 221; 221, call; 221, 222; 221, 225; 222, attribute; 222, 223; 222, 224; 223, identifier:class_methods; 224, identifier:append; 225, argument_list; 225, 226; 226, identifier:node; 227, expression_statement; 227, 228; 228, assignment; 228, 229; 228, 230; 229, identifier:class_vars; 230, list:[]; 231, expression_statement; 231, 232; 232, assignment; 232, 233; 232, 234; 233, identifier:self_vars; 234, list:[]; 235, for_statement; 235, 236; 235, 237; 235, 238; 236, identifier:method_node; 237, identifier:class_methods; 238, block; 238, 239; 238, 251; 238, 258; 239, expression_statement; 239, 240; 240, assignment; 240, 241; 240, 242; 241, identifier:self_var; 242, call; 242, 243; 242, 250; 243, attribute; 243, 244; 243, 249; 244, subscript; 244, 245; 244, 248; 245, attribute; 245, 246; 245, 247; 246, identifier:method_node; 247, identifier:arguments; 248, integer:0; 249, identifier:dumps; 250, argument_list; 251, expression_statement; 251, 252; 252, call; 252, 253; 252, 256; 253, attribute; 253, 254; 253, 255; 254, identifier:self_vars; 255, identifier:append; 256, argument_list; 256, 257; 257, identifier:self_var; 258, for_statement; 258, 259; 258, 260; 258, 266; 258, 267; 259, identifier:assign; 260, call; 260, 261; 260, 264; 261, attribute; 261, 262; 261, 263; 262, identifier:method_node; 263, identifier:find_all; 264, argument_list; 264, 265; 265, string:'assignment'; 266, comment; 267, block; 267, 268; 268, if_statement; 268, 269; 268, 283; 269, call; 269, 270; 269, 279; 270, attribute; 270, 271; 270, 278; 271, call; 271, 272; 271, 277; 272, attribute; 272, 273; 272, 276; 273, attribute; 273, 274; 273, 275; 274, identifier:assign; 275, identifier:target; 276, identifier:dumps; 277, argument_list; 278, identifier:startswith; 279, argument_list; 279, 280; 280, binary_operator:+; 280, 281; 280, 282; 281, identifier:self_var; 282, string:'.'; 283, block; 283, 284; 284, expression_statement; 284, 285; 285, call; 285, 286; 285, 289; 286, attribute; 286, 287; 286, 288; 287, identifier:class_vars; 288, identifier:append; 289, argument_list; 289, 290; 290, call; 290, 291; 290, 300; 291, attribute; 291, 292; 291, 299; 292, subscript; 292, 293; 292, 298; 293, attribute; 293, 294; 293, 297; 294, attribute; 294, 295; 294, 296; 295, identifier:assign; 296, identifier:target; 297, identifier:value; 298, integer:1; 299, identifier:dumps; 300, argument_list; 301, expression_statement; 301, 302; 302, assignment; 302, 303; 302, 304; 303, identifier:static_attrs; 304, call; 304, 305; 304, 308; 305, attribute; 305, 306; 305, 307; 306, identifier:ut; 307, identifier:unique; 308, argument_list; 308, 309; 309, identifier:class_vars; 310, return_statement; 310, 311; 311, identifier:static_attrs; 312, comment; 313, if_statement; 313, 314; 313, 315; 314, False; 315, block; 315, 316; 315, 322; 315, 323; 315, 327; 315, 331; 315, 352; 315, 416; 315, 420; 315, 456; 315, 465; 316, expression_statement; 316, 317; 317, assignment; 317, 318; 317, 319; 318, identifier:self_var; 319, subscript; 319, 320; 319, 321; 320, identifier:self_vars; 321, integer:0; 322, comment; 323, expression_statement; 323, 324; 324, assignment; 324, 325; 324, 326; 325, identifier:complex_cases; 326, list:[]; 327, expression_statement; 327, 328; 328, assignment; 328, 329; 328, 330; 329, identifier:simple_cases; 330, list:[]; 331, expression_statement; 331, 332; 332, assignment; 332, 333; 332, 334; 333, identifier:all_self_ref; 334, call; 334, 335; 334, 338; 335, attribute; 335, 336; 335, 337; 336, identifier:classnode; 337, identifier:find_all; 338, argument_list; 338, 339; 338, 340; 339, string:'name_'; 340, keyword_argument; 340, 341; 340, 342; 341, identifier:value; 342, call; 342, 343; 342, 346; 343, attribute; 343, 344; 343, 345; 344, identifier:re; 345, identifier:compile; 346, argument_list; 346, 347; 347, binary_operator:+; 347, 348; 347, 351; 348, binary_operator:+; 348, 349; 348, 350; 349, string:'.*'; 350, identifier:self_var; 351, string:'\\.*'; 352, for_statement; 352, 353; 352, 354; 352, 355; 353, identifier:x; 354, identifier:all_self_ref; 355, block; 355, 356; 355, 366; 356, if_statement; 356, 357; 356, 364; 357, comparison_operator:==; 357, 358; 357, 363; 358, attribute; 358, 359; 358, 362; 359, attribute; 359, 360; 359, 361; 360, identifier:x; 361, identifier:parent; 362, identifier:type; 363, string:'def_argument'; 364, block; 364, 365; 365, continue_statement; 366, if_statement; 366, 367; 366, 374; 367, comparison_operator:==; 367, 368; 367, 373; 368, attribute; 368, 369; 368, 372; 369, attribute; 369, 370; 369, 371; 370, identifier:x; 371, identifier:parent; 372, identifier:type; 373, string:'atomtrailers'; 374, block; 374, 375; 374, 381; 374, 411; 374, 412; 374, 413; 374, 414; 374, 415; 375, expression_statement; 375, 376; 376, assignment; 376, 377; 376, 378; 377, identifier:atom; 378, attribute; 378, 379; 378, 380; 379, identifier:x; 380, identifier:parent; 381, if_statement; 381, 382; 381, 394; 381, 402; 382, comparison_operator:<=; 382, 383; 382, 393; 383, call; 383, 384; 383, 387; 384, attribute; 384, 385; 384, 386; 385, identifier:ut; 386, identifier:depth; 387, argument_list; 387, 388; 388, call; 388, 389; 388, 392; 389, attribute; 389, 390; 389, 391; 390, identifier:atom; 391, identifier:fst; 392, argument_list; 393, integer:3; 394, block; 394, 395; 395, expression_statement; 395, 396; 396, call; 396, 397; 396, 400; 397, attribute; 397, 398; 397, 399; 398, identifier:simple_cases; 399, identifier:append; 400, argument_list; 400, 401; 401, identifier:atom; 402, else_clause; 402, 403; 403, block; 403, 404; 404, expression_statement; 404, 405; 405, call; 405, 406; 405, 409; 406, attribute; 406, 407; 406, 408; 407, identifier:complex_cases; 408, identifier:append; 409, argument_list; 409, 410; 410, identifier:atom; 411, comment; 412, comment; 413, comment; 414, comment; 415, comment; 416, expression_statement; 416, 417; 417, assignment; 417, 418; 417, 419; 418, identifier:accessed_attrs; 419, list:[]; 420, for_statement; 420, 421; 420, 422; 420, 423; 421, identifier:x; 422, identifier:simple_cases; 423, block; 423, 424; 424, if_statement; 424, 425; 424, 436; 425, comparison_operator:==; 425, 426; 425, 435; 426, call; 426, 427; 426, 434; 427, attribute; 427, 428; 427, 433; 428, subscript; 428, 429; 428, 432; 429, attribute; 429, 430; 429, 431; 430, identifier:x; 431, identifier:value; 432, integer:0; 433, identifier:dumps; 434, argument_list; 435, identifier:self_var; 436, block; 436, 437; 436, 449; 437, expression_statement; 437, 438; 438, assignment; 438, 439; 438, 440; 439, identifier:attr; 440, call; 440, 441; 440, 448; 441, attribute; 441, 442; 441, 447; 442, subscript; 442, 443; 442, 446; 443, attribute; 443, 444; 443, 445; 444, identifier:x; 445, identifier:value; 446, integer:1; 447, identifier:dumps; 448, argument_list; 449, expression_statement; 449, 450; 450, call; 450, 451; 450, 454; 451, attribute; 451, 452; 451, 453; 452, identifier:accessed_attrs; 453, identifier:append; 454, argument_list; 454, 455; 455, identifier:attr; 456, expression_statement; 456, 457; 457, assignment; 457, 458; 457, 459; 458, identifier:accessed_attrs; 459, call; 459, 460; 459, 463; 460, attribute; 460, 461; 460, 462; 461, identifier:ut; 462, identifier:unique; 463, argument_list; 463, 464; 464, identifier:accessed_attrs; 465, expression_statement; 465, 466; 466, call; 466, 467; 466, 470; 467, attribute; 467, 468; 467, 469; 468, identifier:ut; 469, identifier:setdiff; 470, argument_list; 470, 471; 470, 472; 471, identifier:accessed_attrs; 472, identifier:class_vars
def check_static_member_vars(class_, fpath=None, only_init=True): """ class_ can either be live object or a classname # fpath = ut.truepath('~/code/ibeis/ibeis/viz/viz_graph2.py') # classname = 'AnnotGraphWidget' """ #import ast #import astor import utool as ut if isinstance(class_, six.string_types): classname = class_ if fpath is None: raise Exception('must specify fpath') else: # We were given a live object if not isinstance(class_, type): # We were given the class instance not the class class_instance = class_ class_ = class_instance.__class__ classname = class_.__name__ if fpath is None: module = ut.get_module_from_class(class_) fpath = ut.get_modpath(module) sourcecode = ut.readfrom(fpath) import redbaron # Pares a FULL syntax tree that keeps blockcomments baron = redbaron.RedBaron(sourcecode) for node in baron: if node.type == 'class' and node.name == classname: classnode = node break def find_parent_method(node): par = node.parent_find('def') if par is not None and par.parent is not None: if par.parent.type == 'class': return par else: return find_parent_method(par) # TODO: Find inherited attrs #classnode.inherit_from # inhertied_attrs = ['parent'] # inhertied_attrs = [] class_methods = [] for node in classnode: if node.type == 'def': if only_init: if node.name == '__init__': class_methods.append(node) else: class_methods.append(node) class_vars = [] self_vars = [] for method_node in class_methods: self_var = method_node.arguments[0].dumps() self_vars.append(self_var) for assign in method_node.find_all('assignment'): # method_node = find_parent_method(assign) if assign.target.dumps().startswith(self_var + '.'): class_vars.append(assign.target.value[1].dumps()) static_attrs = ut.unique(class_vars) return static_attrs # class_members = ut.unique(class_vars + class_methods + inhertied_attrs) if False: self_var = self_vars[0] # Find everything that is used complex_cases = [] simple_cases = [] all_self_ref = classnode.find_all( 'name_', value=re.compile('.*' + self_var + '\\.*')) for x in all_self_ref: if x.parent.type == 'def_argument': continue if x.parent.type == 'atomtrailers': atom = x.parent if ut.depth(atom.fst()) <= 3: simple_cases.append(atom) else: complex_cases.append(atom) #print(ut.depth(atom.value.data)) #print(atom.value) #print(atom.dumps()) #if len(atom.dumps()) > 200: # break accessed_attrs = [] for x in simple_cases: if x.value[0].dumps() == self_var: attr = x.value[1].dumps() accessed_attrs.append(attr) accessed_attrs = ut.unique(accessed_attrs) ut.setdiff(accessed_attrs, class_vars)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 8; 2, function_name:get_funcnames_from_modpath; 3, parameters; 3, 4; 3, 5; 4, identifier:modpath; 5, default_parameter; 5, 6; 5, 7; 6, identifier:include_methods; 7, True; 8, block; 8, 9; 8, 11; 8, 16; 8, 169; 9, expression_statement; 9, 10; 10, comment; 11, import_statement; 11, 12; 12, aliased_import; 12, 13; 12, 15; 13, dotted_name; 13, 14; 14, identifier:utool; 15, identifier:ut; 16, if_statement; 16, 17; 16, 18; 16, 117; 17, True; 18, block; 18, 19; 18, 22; 18, 31; 18, 32; 18, 41; 18, 57; 19, import_statement; 19, 20; 20, dotted_name; 20, 21; 21, identifier:jedi; 22, expression_statement; 22, 23; 23, assignment; 23, 24; 23, 25; 24, identifier:source; 25, call; 25, 26; 25, 29; 26, attribute; 26, 27; 26, 28; 27, identifier:ut; 28, identifier:read_from; 29, argument_list; 29, 30; 30, identifier:modpath; 31, comment; 32, expression_statement; 32, 33; 33, assignment; 33, 34; 33, 35; 34, identifier:definition_list; 35, call; 35, 36; 35, 39; 36, attribute; 36, 37; 36, 38; 37, identifier:jedi; 38, identifier:names; 39, argument_list; 39, 40; 40, identifier:source; 41, expression_statement; 41, 42; 42, assignment; 42, 43; 42, 44; 43, identifier:funcname_list; 44, list_comprehension; 44, 45; 44, 48; 44, 51; 45, attribute; 45, 46; 45, 47; 46, identifier:definition; 47, identifier:name; 48, for_in_clause; 48, 49; 48, 50; 49, identifier:definition; 50, identifier:definition_list; 51, if_clause; 51, 52; 52, comparison_operator:==; 52, 53; 52, 56; 53, attribute; 53, 54; 53, 55; 54, identifier:definition; 55, identifier:type; 56, string:'function'; 57, if_statement; 57, 58; 57, 59; 58, identifier:include_methods; 59, block; 59, 60; 59, 74; 59, 91; 60, expression_statement; 60, 61; 61, assignment; 61, 62; 61, 63; 62, identifier:classdef_list; 63, list_comprehension; 63, 64; 63, 65; 63, 68; 64, identifier:definition; 65, for_in_clause; 65, 66; 65, 67; 66, identifier:definition; 67, identifier:definition_list; 68, if_clause; 68, 69; 69, comparison_operator:==; 69, 70; 69, 73; 70, attribute; 70, 71; 70, 72; 71, identifier:definition; 72, identifier:type; 73, string:'class'; 74, expression_statement; 74, 75; 75, assignment; 75, 76; 75, 77; 76, identifier:defined_methods; 77, call; 77, 78; 77, 81; 78, attribute; 78, 79; 78, 80; 79, identifier:ut; 80, identifier:flatten; 81, argument_list; 81, 82; 82, list_comprehension; 82, 83; 82, 88; 83, call; 83, 84; 83, 87; 84, attribute; 84, 85; 84, 86; 85, identifier:definition; 86, identifier:defined_names; 87, argument_list; 88, for_in_clause; 88, 89; 88, 90; 89, identifier:definition; 90, identifier:classdef_list; 91, expression_statement; 91, 92; 92, augmented_assignment:+=; 92, 93; 92, 94; 93, identifier:funcname_list; 94, list_comprehension; 94, 95; 94, 98; 94, 101; 95, attribute; 95, 96; 95, 97; 96, identifier:method; 97, identifier:name; 98, for_in_clause; 98, 99; 98, 100; 99, identifier:method; 100, identifier:defined_methods; 101, if_clause; 101, 102; 102, boolean_operator:and; 102, 103; 102, 108; 103, comparison_operator:==; 103, 104; 103, 107; 104, attribute; 104, 105; 104, 106; 105, identifier:method; 106, identifier:type; 107, string:'function'; 108, not_operator; 108, 109; 109, call; 109, 110; 109, 115; 110, attribute; 110, 111; 110, 114; 111, attribute; 111, 112; 111, 113; 112, identifier:method; 113, identifier:name; 114, identifier:startswith; 115, argument_list; 115, 116; 116, string:'_'; 117, else_clause; 117, 118; 118, block; 118, 119; 118, 122; 118, 123; 118, 132; 118, 141; 119, import_statement; 119, 120; 120, dotted_name; 120, 121; 121, identifier:redbaron; 122, comment; 123, expression_statement; 123, 124; 124, assignment; 124, 125; 124, 126; 125, identifier:sourcecode; 126, call; 126, 127; 126, 130; 127, attribute; 127, 128; 127, 129; 128, identifier:ut; 129, identifier:read_from; 130, argument_list; 130, 131; 131, identifier:modpath; 132, expression_statement; 132, 133; 133, assignment; 133, 134; 133, 135; 134, identifier:baron; 135, call; 135, 136; 135, 139; 136, attribute; 136, 137; 136, 138; 137, identifier:redbaron; 138, identifier:RedBaron; 139, argument_list; 139, 140; 140, identifier:sourcecode; 141, expression_statement; 141, 142; 142, assignment; 142, 143; 142, 144; 143, identifier:funcname_list; 144, list_comprehension; 144, 145; 144, 148; 144, 159; 145, attribute; 145, 146; 145, 147; 146, identifier:node; 147, identifier:name; 148, for_in_clause; 148, 149; 148, 150; 149, identifier:node; 150, call; 150, 151; 150, 154; 151, attribute; 151, 152; 151, 153; 152, identifier:baron; 153, identifier:find_all; 154, argument_list; 154, 155; 154, 156; 155, string:'def'; 156, keyword_argument; 156, 157; 156, 158; 157, identifier:recursive; 158, identifier:include_methods; 159, if_clause; 159, 160; 160, not_operator; 160, 161; 161, call; 161, 162; 161, 167; 162, attribute; 162, 163; 162, 166; 163, attribute; 163, 164; 163, 165; 164, identifier:node; 165, identifier:name; 166, identifier:startswith; 167, argument_list; 167, 168; 168, string:'_'; 169, return_statement; 169, 170; 170, identifier:funcname_list
def get_funcnames_from_modpath(modpath, include_methods=True): """ Get all functions defined in module """ import utool as ut if True: import jedi source = ut.read_from(modpath) #script = jedi.Script(source=source, source_path=modpath, line=source.count('\n') + 1) definition_list = jedi.names(source) funcname_list = [definition.name for definition in definition_list if definition.type == 'function'] if include_methods: classdef_list = [definition for definition in definition_list if definition.type == 'class'] defined_methods = ut.flatten([definition.defined_names() for definition in classdef_list]) funcname_list += [method.name for method in defined_methods if method.type == 'function' and not method.name.startswith('_')] else: import redbaron # Pares a FULL syntax tree that keeps blockcomments sourcecode = ut.read_from(modpath) baron = redbaron.RedBaron(sourcecode) funcname_list = [node.name for node in baron.find_all('def', recursive=include_methods) if not node.name.startswith('_')] return funcname_list
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 9; 2, function_name:is_defined_by_module; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:item; 5, identifier:module; 6, default_parameter; 6, 7; 6, 8; 7, identifier:parent; 8, None; 9, block; 9, 10; 9, 12; 9, 16; 9, 281; 10, expression_statement; 10, 11; 11, comment; 12, expression_statement; 12, 13; 13, assignment; 13, 14; 13, 15; 14, identifier:flag; 15, False; 16, if_statement; 16, 17; 16, 24; 16, 145; 16, 170; 17, call; 17, 18; 17, 19; 18, identifier:isinstance; 19, argument_list; 19, 20; 19, 21; 20, identifier:item; 21, attribute; 21, 22; 21, 23; 22, identifier:types; 23, identifier:ModuleType; 24, block; 24, 25; 25, if_statement; 25, 26; 25, 32; 25, 67; 26, not_operator; 26, 27; 27, call; 27, 28; 27, 29; 28, identifier:hasattr; 29, argument_list; 29, 30; 29, 31; 30, identifier:item; 31, string:'__file__'; 32, block; 32, 33; 33, try_statement; 33, 34; 33, 35; 33, 61; 34, comment; 35, block; 35, 36; 35, 41; 35, 52; 36, import_statement; 36, 37; 37, aliased_import; 37, 38; 37, 40; 38, dotted_name; 38, 39; 39, identifier:utool; 40, identifier:ut; 41, expression_statement; 41, 42; 42, assignment; 42, 43; 42, 44; 43, identifier:name; 44, call; 44, 45; 44, 48; 45, attribute; 45, 46; 45, 47; 46, identifier:ut; 47, identifier:get_modname_from_modpath; 48, argument_list; 48, 49; 49, attribute; 49, 50; 49, 51; 50, identifier:module; 51, identifier:__file__; 52, expression_statement; 52, 53; 53, assignment; 53, 54; 53, 55; 54, identifier:flag; 55, comparison_operator:in; 55, 56; 55, 57; 56, identifier:name; 57, call; 57, 58; 57, 59; 58, identifier:str; 59, argument_list; 59, 60; 60, identifier:item; 61, except_clause; 61, 62; 62, block; 62, 63; 63, expression_statement; 63, 64; 64, assignment; 64, 65; 64, 66; 65, identifier:flag; 66, False; 67, else_clause; 67, 68; 68, block; 68, 69; 68, 85; 68, 97; 69, expression_statement; 69, 70; 70, assignment; 70, 71; 70, 72; 71, identifier:item_modpath; 72, call; 72, 73; 72, 78; 73, attribute; 73, 74; 73, 77; 74, attribute; 74, 75; 74, 76; 75, identifier:os; 76, identifier:path; 77, identifier:realpath; 78, argument_list; 78, 79; 79, call; 79, 80; 79, 81; 80, identifier:dirname; 81, argument_list; 81, 82; 82, attribute; 82, 83; 82, 84; 83, identifier:item; 84, identifier:__file__; 85, expression_statement; 85, 86; 86, assignment; 86, 87; 86, 88; 87, identifier:mod_fpath; 88, call; 88, 89; 88, 94; 89, attribute; 89, 90; 89, 93; 90, attribute; 90, 91; 90, 92; 91, identifier:module; 92, identifier:__file__; 93, identifier:replace; 94, argument_list; 94, 95; 94, 96; 95, string:'.pyc'; 96, string:'.py'; 97, if_statement; 97, 98; 97, 105; 97, 110; 98, not_operator; 98, 99; 99, call; 99, 100; 99, 103; 100, attribute; 100, 101; 100, 102; 101, identifier:mod_fpath; 102, identifier:endswith; 103, argument_list; 103, 104; 104, string:'__init__.py'; 105, block; 105, 106; 106, expression_statement; 106, 107; 107, assignment; 107, 108; 107, 109; 108, identifier:flag; 109, False; 110, else_clause; 110, 111; 111, block; 111, 112; 111, 126; 111, 136; 112, expression_statement; 112, 113; 113, assignment; 113, 114; 113, 115; 114, identifier:modpath; 115, call; 115, 116; 115, 121; 116, attribute; 116, 117; 116, 120; 117, attribute; 117, 118; 117, 119; 118, identifier:os; 119, identifier:path; 120, identifier:realpath; 121, argument_list; 121, 122; 122, call; 122, 123; 122, 124; 123, identifier:dirname; 124, argument_list; 124, 125; 125, identifier:mod_fpath; 126, expression_statement; 126, 127; 127, assignment; 127, 128; 127, 129; 128, identifier:modpath; 129, call; 129, 130; 129, 133; 130, attribute; 130, 131; 130, 132; 131, identifier:modpath; 132, identifier:replace; 133, argument_list; 133, 134; 133, 135; 134, string:'.pyc'; 135, string:'.py'; 136, expression_statement; 136, 137; 137, assignment; 137, 138; 137, 139; 138, identifier:flag; 139, call; 139, 140; 139, 143; 140, attribute; 140, 141; 140, 142; 141, identifier:item_modpath; 142, identifier:startswith; 143, argument_list; 143, 144; 144, identifier:modpath; 145, elif_clause; 145, 146; 145, 151; 145, 152; 146, call; 146, 147; 146, 148; 147, identifier:hasattr; 148, argument_list; 148, 149; 148, 150; 149, identifier:item; 150, string:'_utinfo'; 151, comment; 152, block; 152, 153; 152, 161; 153, expression_statement; 153, 154; 154, assignment; 154, 155; 154, 156; 155, identifier:orig_func; 156, subscript; 156, 157; 156, 160; 157, attribute; 157, 158; 157, 159; 158, identifier:item; 159, identifier:_utinfo; 160, string:'orig_func'; 161, expression_statement; 161, 162; 162, assignment; 162, 163; 162, 164; 163, identifier:flag; 164, call; 164, 165; 164, 166; 165, identifier:is_defined_by_module; 166, argument_list; 166, 167; 166, 168; 166, 169; 167, identifier:orig_func; 168, identifier:module; 169, identifier:parent; 170, else_clause; 170, 171; 171, block; 171, 172; 171, 186; 172, if_statement; 172, 173; 172, 178; 172, 179; 173, call; 173, 174; 173, 175; 174, identifier:isinstance; 175, argument_list; 175, 176; 175, 177; 176, identifier:item; 177, identifier:staticmethod; 178, comment; 179, block; 179, 180; 180, expression_statement; 180, 181; 181, assignment; 181, 182; 181, 183; 182, identifier:item; 183, attribute; 183, 184; 183, 185; 184, identifier:item; 185, identifier:__func__; 186, try_statement; 186, 187; 186, 261; 187, block; 187, 188; 187, 197; 187, 203; 188, expression_statement; 188, 189; 189, assignment; 189, 190; 189, 191; 190, identifier:func_globals; 191, call; 191, 192; 191, 195; 192, attribute; 192, 193; 192, 194; 193, identifier:meta_util_six; 194, identifier:get_funcglobals; 195, argument_list; 195, 196; 196, identifier:item; 197, expression_statement; 197, 198; 198, assignment; 198, 199; 198, 200; 199, identifier:func_module_name; 200, subscript; 200, 201; 200, 202; 201, identifier:func_globals; 202, string:'__name__'; 203, if_statement; 203, 204; 203, 207; 203, 250; 204, comparison_operator:==; 204, 205; 204, 206; 205, identifier:func_module_name; 206, string:'line_profiler'; 207, block; 207, 208; 207, 215; 207, 227; 208, expression_statement; 208, 209; 209, assignment; 209, 210; 209, 211; 210, identifier:valid_names; 211, call; 211, 212; 211, 213; 212, identifier:dir; 213, argument_list; 213, 214; 214, identifier:module; 215, if_statement; 215, 216; 215, 219; 216, comparison_operator:is; 216, 217; 216, 218; 217, identifier:parent; 218, None; 219, block; 219, 220; 220, expression_statement; 220, 221; 221, augmented_assignment:+=; 221, 222; 221, 223; 222, identifier:valid_names; 223, call; 223, 224; 223, 225; 224, identifier:dir; 225, argument_list; 225, 226; 226, identifier:parent; 227, if_statement; 227, 228; 227, 233; 227, 234; 227, 235; 228, comparison_operator:in; 228, 229; 228, 232; 229, attribute; 229, 230; 229, 231; 230, identifier:item; 231, identifier:func_name; 232, identifier:valid_names; 233, comment; 234, comment; 235, block; 235, 236; 236, if_statement; 236, 237; 236, 245; 237, comparison_operator:>; 237, 238; 237, 244; 238, call; 238, 239; 238, 240; 239, identifier:len; 240, argument_list; 240, 241; 241, attribute; 241, 242; 241, 243; 242, identifier:item; 243, identifier:func_name; 244, integer:6; 245, block; 245, 246; 246, expression_statement; 246, 247; 247, assignment; 247, 248; 247, 249; 248, identifier:flag; 249, True; 250, elif_clause; 250, 251; 250, 256; 251, comparison_operator:==; 251, 252; 251, 253; 252, identifier:func_module_name; 253, attribute; 253, 254; 253, 255; 254, identifier:module; 255, identifier:__name__; 256, block; 256, 257; 257, expression_statement; 257, 258; 258, assignment; 258, 259; 258, 260; 259, identifier:flag; 260, True; 261, except_clause; 261, 262; 261, 263; 262, identifier:AttributeError; 263, block; 263, 264; 264, if_statement; 264, 265; 264, 270; 265, call; 265, 266; 265, 267; 266, identifier:hasattr; 267, argument_list; 267, 268; 267, 269; 268, identifier:item; 269, string:'__module__'; 270, block; 270, 271; 271, expression_statement; 271, 272; 272, assignment; 272, 273; 272, 274; 273, identifier:flag; 274, comparison_operator:==; 274, 275; 274, 278; 275, attribute; 275, 276; 275, 277; 276, identifier:item; 277, identifier:__module__; 278, attribute; 278, 279; 278, 280; 279, identifier:module; 280, identifier:__name__; 281, return_statement; 281, 282; 282, identifier:flag
def is_defined_by_module(item, module, parent=None): """ Check if item is directly defined by a module. This check may be prone to errors. """ flag = False if isinstance(item, types.ModuleType): if not hasattr(item, '__file__'): try: # hack for cv2 and xfeatures2d import utool as ut name = ut.get_modname_from_modpath(module.__file__) flag = name in str(item) except: flag = False else: item_modpath = os.path.realpath(dirname(item.__file__)) mod_fpath = module.__file__.replace('.pyc', '.py') if not mod_fpath.endswith('__init__.py'): flag = False else: modpath = os.path.realpath(dirname(mod_fpath)) modpath = modpath.replace('.pyc', '.py') flag = item_modpath.startswith(modpath) elif hasattr(item, '_utinfo'): # Capture case where there is a utool wrapper orig_func = item._utinfo['orig_func'] flag = is_defined_by_module(orig_func, module, parent) else: if isinstance(item, staticmethod): # static methods are a wrapper around a function item = item.__func__ try: func_globals = meta_util_six.get_funcglobals(item) func_module_name = func_globals['__name__'] if func_module_name == 'line_profiler': valid_names = dir(module) if parent is not None: valid_names += dir(parent) if item.func_name in valid_names: # hack to prevent small names #if len(item.func_name) > 8: if len(item.func_name) > 6: flag = True elif func_module_name == module.__name__: flag = True except AttributeError: if hasattr(item, '__module__'): flag = item.__module__ == module.__name__ return flag
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 8; 2, function_name:find_funcs_called_with_kwargs; 3, parameters; 3, 4; 3, 5; 4, identifier:sourcecode; 5, default_parameter; 5, 6; 5, 7; 6, identifier:target_kwargs_name; 7, string:'kwargs'; 8, block; 8, 9; 8, 11; 8, 14; 8, 20; 8, 29; 8, 33; 8, 39; 8, 83; 8, 405; 8, 424; 9, expression_statement; 9, 10; 10, comment; 11, import_statement; 11, 12; 12, dotted_name; 12, 13; 13, identifier:ast; 14, expression_statement; 14, 15; 15, assignment; 15, 16; 15, 17; 16, identifier:sourcecode; 17, binary_operator:+; 17, 18; 17, 19; 18, string:'from __future__ import print_function\n'; 19, identifier:sourcecode; 20, expression_statement; 20, 21; 21, assignment; 21, 22; 21, 23; 22, identifier:pt; 23, call; 23, 24; 23, 27; 24, attribute; 24, 25; 24, 26; 25, identifier:ast; 26, identifier:parse; 27, argument_list; 27, 28; 28, identifier:sourcecode; 29, expression_statement; 29, 30; 30, assignment; 30, 31; 30, 32; 31, identifier:child_funcnamess; 32, list:[]; 33, expression_statement; 33, 34; 34, assignment; 34, 35; 34, 36; 35, identifier:debug; 36, boolean_operator:or; 36, 37; 36, 38; 37, False; 38, identifier:VERYVERB_INSPECT; 39, if_statement; 39, 40; 39, 41; 40, identifier:debug; 41, block; 41, 42; 41, 47; 41, 55; 41, 60; 41, 65; 41, 68; 41, 73; 42, expression_statement; 42, 43; 43, call; 43, 44; 43, 45; 44, identifier:print; 45, argument_list; 45, 46; 46, string:'\nInput:'; 47, expression_statement; 47, 48; 48, call; 48, 49; 48, 50; 49, identifier:print; 50, argument_list; 50, 51; 51, binary_operator:%; 51, 52; 51, 53; 52, string:'target_kwargs_name = %r'; 53, tuple; 53, 54; 54, identifier:target_kwargs_name; 55, expression_statement; 55, 56; 56, call; 56, 57; 56, 58; 57, identifier:print; 58, argument_list; 58, 59; 59, string:'\nSource:'; 60, expression_statement; 60, 61; 61, call; 61, 62; 61, 63; 62, identifier:print; 63, argument_list; 63, 64; 64, identifier:sourcecode; 65, import_statement; 65, 66; 66, dotted_name; 66, 67; 67, identifier:astor; 68, expression_statement; 68, 69; 69, call; 69, 70; 69, 71; 70, identifier:print; 71, argument_list; 71, 72; 72, string:'\nParse:'; 73, expression_statement; 73, 74; 74, call; 74, 75; 74, 76; 75, identifier:print; 76, argument_list; 76, 77; 77, call; 77, 78; 77, 81; 78, attribute; 78, 79; 78, 80; 79, identifier:astor; 80, identifier:dump; 81, argument_list; 81, 82; 82, identifier:pt; 83, class_definition; 83, 84; 83, 85; 83, 89; 84, identifier:KwargParseVisitor; 85, argument_list; 85, 86; 86, attribute; 86, 87; 86, 88; 87, identifier:ast; 88, identifier:NodeVisitor; 89, block; 89, 90; 89, 92; 89, 179; 90, expression_statement; 90, 91; 91, comment; 92, function_definition; 92, 93; 92, 94; 92, 97; 93, function_name:visit_FunctionDef; 94, parameters; 94, 95; 94, 96; 95, identifier:self; 96, identifier:node; 97, block; 97, 98; 97, 121; 97, 163; 98, if_statement; 98, 99; 98, 100; 99, identifier:debug; 100, block; 100, 101; 100, 109; 101, expression_statement; 101, 102; 102, call; 102, 103; 102, 104; 103, identifier:print; 104, argument_list; 104, 105; 105, binary_operator:%; 105, 106; 105, 107; 106, string:'\nVISIT FunctionDef node = %r'; 107, tuple; 107, 108; 108, identifier:node; 109, expression_statement; 109, 110; 110, call; 110, 111; 110, 112; 111, identifier:print; 112, argument_list; 112, 113; 113, binary_operator:%; 113, 114; 113, 115; 114, string:'node.args.kwarg = %r'; 115, tuple; 115, 116; 116, attribute; 116, 117; 116, 120; 117, attribute; 117, 118; 117, 119; 118, identifier:node; 119, identifier:args; 120, identifier:kwarg; 121, if_statement; 121, 122; 121, 125; 121, 134; 122, attribute; 122, 123; 122, 124; 123, identifier:six; 124, identifier:PY2; 125, block; 125, 126; 126, expression_statement; 126, 127; 127, assignment; 127, 128; 127, 129; 128, identifier:kwarg_name; 129, attribute; 129, 130; 129, 133; 130, attribute; 130, 131; 130, 132; 131, identifier:node; 132, identifier:args; 133, identifier:kwarg; 134, else_clause; 134, 135; 135, block; 135, 136; 135, 161; 135, 162; 136, if_statement; 136, 137; 136, 144; 136, 149; 137, comparison_operator:is; 137, 138; 137, 143; 138, attribute; 138, 139; 138, 142; 139, attribute; 139, 140; 139, 141; 140, identifier:node; 141, identifier:args; 142, identifier:kwarg; 143, None; 144, block; 144, 145; 145, expression_statement; 145, 146; 146, assignment; 146, 147; 146, 148; 147, identifier:kwarg_name; 148, None; 149, else_clause; 149, 150; 150, block; 150, 151; 151, expression_statement; 151, 152; 152, assignment; 152, 153; 152, 154; 153, identifier:kwarg_name; 154, attribute; 154, 155; 154, 160; 155, attribute; 155, 156; 155, 159; 156, attribute; 156, 157; 156, 158; 157, identifier:node; 158, identifier:args; 159, identifier:kwarg; 160, identifier:arg; 161, comment; 162, comment; 163, if_statement; 163, 164; 163, 167; 163, 168; 164, comparison_operator:!=; 164, 165; 164, 166; 165, identifier:kwarg_name; 166, identifier:target_kwargs_name; 167, comment; 168, block; 168, 169; 169, expression_statement; 169, 170; 170, call; 170, 171; 170, 176; 171, attribute; 171, 172; 171, 175; 172, attribute; 172, 173; 172, 174; 173, identifier:ast; 174, identifier:NodeVisitor; 175, identifier:generic_visit; 176, argument_list; 176, 177; 176, 178; 177, identifier:self; 178, identifier:node; 179, function_definition; 179, 180; 179, 181; 179, 184; 180, function_name:visit_Call; 181, parameters; 181, 182; 181, 183; 182, identifier:self; 183, identifier:node; 184, block; 184, 185; 184, 197; 184, 266; 184, 395; 185, if_statement; 185, 186; 185, 187; 186, identifier:debug; 187, block; 187, 188; 187, 196; 188, expression_statement; 188, 189; 189, call; 189, 190; 189, 191; 190, identifier:print; 191, argument_list; 191, 192; 192, binary_operator:%; 192, 193; 192, 194; 193, string:'\nVISIT Call node = %r'; 194, tuple; 194, 195; 195, identifier:node; 196, comment; 197, if_statement; 197, 198; 197, 207; 197, 235; 197, 254; 198, call; 198, 199; 198, 200; 199, identifier:isinstance; 200, argument_list; 200, 201; 200, 204; 201, attribute; 201, 202; 201, 203; 202, identifier:node; 203, identifier:func; 204, attribute; 204, 205; 204, 206; 205, identifier:ast; 206, identifier:Attribute; 207, block; 207, 208; 208, try_statement; 208, 209; 208, 228; 209, block; 209, 210; 210, expression_statement; 210, 211; 211, assignment; 211, 212; 211, 213; 212, identifier:funcname; 213, binary_operator:+; 213, 214; 213, 223; 214, binary_operator:+; 214, 215; 214, 222; 215, attribute; 215, 216; 215, 221; 216, attribute; 216, 217; 216, 220; 217, attribute; 217, 218; 217, 219; 218, identifier:node; 219, identifier:func; 220, identifier:value; 221, identifier:id; 222, string:'.'; 223, attribute; 223, 224; 223, 227; 224, attribute; 224, 225; 224, 226; 225, identifier:node; 226, identifier:func; 227, identifier:attr; 228, except_clause; 228, 229; 228, 230; 229, identifier:AttributeError; 230, block; 230, 231; 231, expression_statement; 231, 232; 232, assignment; 232, 233; 232, 234; 233, identifier:funcname; 234, None; 235, elif_clause; 235, 236; 235, 245; 236, call; 236, 237; 236, 238; 237, identifier:isinstance; 238, argument_list; 238, 239; 238, 242; 239, attribute; 239, 240; 239, 241; 240, identifier:node; 241, identifier:func; 242, attribute; 242, 243; 242, 244; 243, identifier:ast; 244, identifier:Name; 245, block; 245, 246; 246, expression_statement; 246, 247; 247, assignment; 247, 248; 247, 249; 248, identifier:funcname; 249, attribute; 249, 250; 249, 253; 250, attribute; 250, 251; 250, 252; 251, identifier:node; 252, identifier:func; 253, identifier:id; 254, else_clause; 254, 255; 255, block; 255, 256; 256, raise_statement; 256, 257; 257, call; 257, 258; 257, 259; 258, identifier:NotImplementedError; 259, argument_list; 259, 260; 260, binary_operator:%; 260, 261; 260, 262; 261, string:'do not know how to parse: node.func = %r'; 262, tuple; 262, 263; 263, attribute; 263, 264; 263, 265; 264, identifier:node; 265, identifier:func; 266, if_statement; 266, 267; 266, 270; 266, 323; 267, attribute; 267, 268; 267, 269; 268, identifier:six; 269, identifier:PY2; 270, block; 270, 271; 270, 277; 270, 288; 270, 304; 271, expression_statement; 271, 272; 272, assignment; 272, 273; 272, 274; 273, identifier:kwargs; 274, attribute; 274, 275; 274, 276; 275, identifier:node; 276, identifier:kwargs; 277, expression_statement; 277, 278; 278, assignment; 278, 279; 278, 280; 279, identifier:kwargs_name; 280, conditional_expression:if; 280, 281; 280, 282; 280, 285; 281, None; 282, comparison_operator:is; 282, 283; 282, 284; 283, identifier:kwargs; 284, None; 285, attribute; 285, 286; 285, 287; 286, identifier:kwargs; 287, identifier:id; 288, if_statement; 288, 289; 288, 296; 289, boolean_operator:and; 289, 290; 289, 293; 290, comparison_operator:is; 290, 291; 290, 292; 291, identifier:funcname; 292, None; 293, comparison_operator:==; 293, 294; 293, 295; 294, identifier:kwargs_name; 295, identifier:target_kwargs_name; 296, block; 296, 297; 297, expression_statement; 297, 298; 298, call; 298, 299; 298, 302; 299, attribute; 299, 300; 299, 301; 300, identifier:child_funcnamess; 301, identifier:append; 302, argument_list; 302, 303; 303, identifier:funcname; 304, if_statement; 304, 305; 304, 306; 305, identifier:debug; 306, block; 306, 307; 306, 315; 307, expression_statement; 307, 308; 308, call; 308, 309; 308, 310; 309, identifier:print; 310, argument_list; 310, 311; 311, binary_operator:%; 311, 312; 311, 313; 312, string:'funcname = %r'; 313, tuple; 313, 314; 314, identifier:funcname; 315, expression_statement; 315, 316; 316, call; 316, 317; 316, 318; 317, identifier:print; 318, argument_list; 318, 319; 319, binary_operator:%; 319, 320; 319, 321; 320, string:'kwargs_name = %r'; 321, tuple; 321, 322; 322, identifier:kwargs_name; 323, else_clause; 323, 324; 324, block; 324, 325; 325, if_statement; 325, 326; 325, 329; 326, attribute; 326, 327; 326, 328; 327, identifier:node; 328, identifier:keywords; 329, block; 329, 330; 330, for_statement; 330, 331; 330, 332; 330, 335; 331, identifier:kwargs; 332, attribute; 332, 333; 332, 334; 333, identifier:node; 334, identifier:keywords; 335, block; 335, 336; 336, if_statement; 336, 337; 336, 342; 337, comparison_operator:is; 337, 338; 337, 341; 338, attribute; 338, 339; 338, 340; 339, identifier:kwargs; 340, identifier:arg; 341, None; 342, block; 342, 343; 343, if_statement; 343, 344; 343, 351; 344, call; 344, 345; 344, 346; 345, identifier:hasattr; 346, argument_list; 346, 347; 346, 350; 347, attribute; 347, 348; 347, 349; 348, identifier:kwargs; 349, identifier:value; 350, string:'id'; 351, block; 351, 352; 351, 360; 351, 376; 352, expression_statement; 352, 353; 353, assignment; 353, 354; 353, 355; 354, identifier:kwargs_name; 355, attribute; 355, 356; 355, 359; 356, attribute; 356, 357; 356, 358; 357, identifier:kwargs; 358, identifier:value; 359, identifier:id; 360, if_statement; 360, 361; 360, 368; 361, boolean_operator:and; 361, 362; 361, 365; 362, comparison_operator:is; 362, 363; 362, 364; 363, identifier:funcname; 364, None; 365, comparison_operator:==; 365, 366; 365, 367; 366, identifier:kwargs_name; 367, identifier:target_kwargs_name; 368, block; 368, 369; 369, expression_statement; 369, 370; 370, call; 370, 371; 370, 374; 371, attribute; 371, 372; 371, 373; 372, identifier:child_funcnamess; 373, identifier:append; 374, argument_list; 374, 375; 375, identifier:funcname; 376, if_statement; 376, 377; 376, 378; 377, identifier:debug; 378, block; 378, 379; 378, 387; 379, expression_statement; 379, 380; 380, call; 380, 381; 380, 382; 381, identifier:print; 382, argument_list; 382, 383; 383, binary_operator:%; 383, 384; 383, 385; 384, string:'funcname = %r'; 385, tuple; 385, 386; 386, identifier:funcname; 387, expression_statement; 387, 388; 388, call; 388, 389; 388, 390; 389, identifier:print; 390, argument_list; 390, 391; 391, binary_operator:%; 391, 392; 391, 393; 392, string:'kwargs_name = %r'; 393, tuple; 393, 394; 394, identifier:kwargs_name; 395, expression_statement; 395, 396; 396, call; 396, 397; 396, 402; 397, attribute; 397, 398; 397, 401; 398, attribute; 398, 399; 398, 400; 399, identifier:ast; 400, identifier:NodeVisitor; 401, identifier:generic_visit; 402, argument_list; 402, 403; 402, 404; 403, identifier:self; 404, identifier:node; 405, try_statement; 405, 406; 405, 416; 406, block; 406, 407; 407, expression_statement; 407, 408; 408, call; 408, 409; 408, 414; 409, attribute; 409, 410; 409, 413; 410, call; 410, 411; 410, 412; 411, identifier:KwargParseVisitor; 412, argument_list; 413, identifier:visit; 414, argument_list; 414, 415; 415, identifier:pt; 416, except_clause; 416, 417; 416, 418; 417, identifier:Exception; 418, block; 418, 419; 418, 420; 418, 421; 418, 422; 418, 423; 419, raise_statement; 420, pass_statement; 421, comment; 422, comment; 423, comment; 424, return_statement; 424, 425; 425, identifier:child_funcnamess
def find_funcs_called_with_kwargs(sourcecode, target_kwargs_name='kwargs'): r""" Finds functions that are called with the keyword `kwargs` variable CommandLine: python3 -m utool.util_inspect find_funcs_called_with_kwargs Example: >>> # ENABLE_DOCTEST >>> import utool as ut >>> sourcecode = ut.codeblock( ''' x, y = list(zip(*ut.ichunks(data, 2))) somecall(arg1, arg2, arg3=4, **kwargs) import sys sys.badcall(**kwargs) def foo(): bar(**kwargs) ut.holymoly(**kwargs) baz() def biz(**kwargs): foo2(**kwargs) ''') >>> child_funcnamess = ut.find_funcs_called_with_kwargs(sourcecode) >>> print('child_funcnamess = %r' % (child_funcnamess,)) >>> assert 'foo2' not in child_funcnamess, 'foo2 should not be found' >>> assert 'bar' in child_funcnamess, 'bar should be found' """ import ast sourcecode = 'from __future__ import print_function\n' + sourcecode pt = ast.parse(sourcecode) child_funcnamess = [] debug = False or VERYVERB_INSPECT if debug: print('\nInput:') print('target_kwargs_name = %r' % (target_kwargs_name,)) print('\nSource:') print(sourcecode) import astor print('\nParse:') print(astor.dump(pt)) class KwargParseVisitor(ast.NodeVisitor): """ TODO: understand ut.update_existing and dict update ie, know when kwargs is passed to these functions and then look assume the object that was updated is a dictionary and check wherever that is passed to kwargs as well. """ def visit_FunctionDef(self, node): if debug: print('\nVISIT FunctionDef node = %r' % (node,)) print('node.args.kwarg = %r' % (node.args.kwarg,)) if six.PY2: kwarg_name = node.args.kwarg else: if node.args.kwarg is None: kwarg_name = None else: kwarg_name = node.args.kwarg.arg #import utool as ut #ut.embed() if kwarg_name != target_kwargs_name: # target kwargs is still in scope ast.NodeVisitor.generic_visit(self, node) def visit_Call(self, node): if debug: print('\nVISIT Call node = %r' % (node,)) #print(ut.repr4(node.__dict__,)) if isinstance(node.func, ast.Attribute): try: funcname = node.func.value.id + '.' + node.func.attr except AttributeError: funcname = None elif isinstance(node.func, ast.Name): funcname = node.func.id else: raise NotImplementedError( 'do not know how to parse: node.func = %r' % (node.func,)) if six.PY2: kwargs = node.kwargs kwargs_name = None if kwargs is None else kwargs.id if funcname is not None and kwargs_name == target_kwargs_name: child_funcnamess.append(funcname) if debug: print('funcname = %r' % (funcname,)) print('kwargs_name = %r' % (kwargs_name,)) else: if node.keywords: for kwargs in node.keywords: if kwargs.arg is None: if hasattr(kwargs.value, 'id'): kwargs_name = kwargs.value.id if funcname is not None and kwargs_name == target_kwargs_name: child_funcnamess.append(funcname) if debug: print('funcname = %r' % (funcname,)) print('kwargs_name = %r' % (kwargs_name,)) ast.NodeVisitor.generic_visit(self, node) try: KwargParseVisitor().visit(pt) except Exception: raise pass #import utool as ut #if ut.SUPER_STRICT: # raise return child_funcnamess
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:_qt_set_leaf_data; 3, parameters; 3, 4; 3, 5; 4, identifier:self; 5, identifier:qvar; 6, block; 6, 7; 6, 9; 6, 79; 6, 93; 6, 487; 7, expression_statement; 7, 8; 8, comment; 9, if_statement; 9, 10; 9, 11; 10, identifier:VERBOSE_PREF; 11, block; 11, 12; 11, 17; 11, 22; 11, 29; 11, 40; 11, 53; 11, 67; 11, 78; 12, expression_statement; 12, 13; 13, call; 13, 14; 13, 15; 14, identifier:print; 15, argument_list; 15, 16; 16, string:''; 17, expression_statement; 17, 18; 18, call; 18, 19; 18, 20; 19, identifier:print; 20, argument_list; 20, 21; 21, string:'+--- [pref.qt_set_leaf_data]'; 22, expression_statement; 22, 23; 23, call; 23, 24; 23, 25; 24, identifier:print; 25, argument_list; 25, 26; 26, binary_operator:%; 26, 27; 26, 28; 27, string:'[pref.qt_set_leaf_data] qvar = %r'; 28, identifier:qvar; 29, expression_statement; 29, 30; 30, call; 30, 31; 30, 32; 31, identifier:print; 32, argument_list; 32, 33; 33, binary_operator:%; 33, 34; 33, 35; 34, string:'[pref.qt_set_leaf_data] _intern.name=%r'; 35, attribute; 35, 36; 35, 39; 36, attribute; 36, 37; 36, 38; 37, identifier:self; 38, identifier:_intern; 39, identifier:name; 40, expression_statement; 40, 41; 41, call; 41, 42; 41, 43; 42, identifier:print; 43, argument_list; 43, 44; 44, binary_operator:%; 44, 45; 44, 46; 45, string:'[pref.qt_set_leaf_data] _intern.type_=%r'; 46, call; 46, 47; 46, 52; 47, attribute; 47, 48; 47, 51; 48, attribute; 48, 49; 48, 50; 49, identifier:self; 50, identifier:_intern; 51, identifier:get_type; 52, argument_list; 53, expression_statement; 53, 54; 54, call; 54, 55; 54, 56; 55, identifier:print; 56, argument_list; 56, 57; 57, binary_operator:%; 57, 58; 57, 59; 58, string:'[pref.qt_set_leaf_data] type(_intern.value)=%r'; 59, call; 59, 60; 59, 61; 60, identifier:type; 61, argument_list; 61, 62; 62, attribute; 62, 63; 62, 66; 63, attribute; 63, 64; 63, 65; 64, identifier:self; 65, identifier:_intern; 66, identifier:value; 67, expression_statement; 67, 68; 68, call; 68, 69; 68, 70; 69, identifier:print; 70, argument_list; 70, 71; 71, binary_operator:%; 71, 72; 71, 73; 72, string:'[pref.qt_set_leaf_data] _intern.value=%r'; 73, attribute; 73, 74; 73, 77; 74, attribute; 74, 75; 74, 76; 75, identifier:self; 76, identifier:_intern; 77, identifier:value; 78, comment; 79, if_statement; 79, 80; 79, 87; 80, comparison_operator:is; 80, 81; 80, 86; 81, attribute; 81, 82; 81, 85; 82, attribute; 82, 83; 82, 84; 83, identifier:self; 84, identifier:_tree; 85, identifier:parent; 86, None; 87, block; 87, 88; 88, raise_statement; 88, 89; 89, call; 89, 90; 89, 91; 90, identifier:Exception; 91, argument_list; 91, 92; 92, string:'[Pref.qtleaf] Cannot set root preference'; 93, if_statement; 93, 94; 93, 99; 94, call; 94, 95; 94, 98; 95, attribute; 95, 96; 95, 97; 96, identifier:self; 97, identifier:qt_is_editable; 98, argument_list; 99, block; 99, 100; 99, 104; 99, 173; 99, 181; 99, 389; 99, 390; 99, 438; 99, 439; 99, 469; 99, 470; 99, 471; 100, expression_statement; 100, 101; 101, assignment; 101, 102; 101, 103; 102, identifier:new_val; 103, string:'[Pref.qtleaf] BadThingsHappenedInPref'; 104, if_statement; 104, 105; 104, 112; 104, 118; 105, comparison_operator:==; 105, 106; 105, 111; 106, attribute; 106, 107; 106, 110; 107, attribute; 107, 108; 107, 109; 108, identifier:self; 109, identifier:_intern; 110, identifier:value; 111, identifier:PrefNode; 112, block; 112, 113; 113, raise_statement; 113, 114; 114, call; 114, 115; 114, 116; 115, identifier:Exception; 116, argument_list; 116, 117; 117, string:'[Pref.qtleaf] Qt can only change leafs'; 118, elif_clause; 118, 119; 118, 126; 118, 127; 119, comparison_operator:is; 119, 120; 119, 125; 120, attribute; 120, 121; 120, 124; 121, attribute; 121, 122; 121, 123; 122, identifier:self; 123, identifier:_intern; 124, identifier:value; 125, None; 126, comment; 127, block; 127, 128; 127, 161; 128, function_definition; 128, 129; 128, 130; 128, 141; 129, function_name:cast_order; 130, parameters; 130, 131; 130, 132; 131, identifier:var; 132, default_parameter; 132, 133; 132, 134; 133, identifier:order; 134, list:[bool, int, float, six.text_type]; 134, 135; 134, 136; 134, 137; 134, 138; 135, identifier:bool; 136, identifier:int; 137, identifier:float; 138, attribute; 138, 139; 138, 140; 139, identifier:six; 140, identifier:text_type; 141, block; 141, 142; 142, for_statement; 142, 143; 142, 144; 142, 145; 143, identifier:type_; 144, identifier:order; 145, block; 145, 146; 146, try_statement; 146, 147; 146, 157; 147, block; 147, 148; 147, 155; 148, expression_statement; 148, 149; 149, assignment; 149, 150; 149, 151; 150, identifier:ret; 151, call; 151, 152; 151, 153; 152, identifier:type_; 153, argument_list; 153, 154; 154, identifier:var; 155, return_statement; 155, 156; 156, identifier:ret; 157, except_clause; 157, 158; 157, 159; 158, identifier:Exception; 159, block; 159, 160; 160, continue_statement; 161, expression_statement; 161, 162; 162, assignment; 162, 163; 162, 164; 163, identifier:new_val; 164, call; 164, 165; 164, 166; 165, identifier:cast_order; 166, argument_list; 166, 167; 167, call; 167, 168; 167, 171; 168, attribute; 168, 169; 168, 170; 169, identifier:six; 170, identifier:text_type; 171, argument_list; 171, 172; 172, identifier:qvar; 173, expression_statement; 173, 174; 174, call; 174, 175; 174, 180; 175, attribute; 175, 176; 175, 179; 176, attribute; 176, 177; 176, 178; 177, identifier:self; 178, identifier:_intern; 179, identifier:get_type; 180, argument_list; 181, if_statement; 181, 182; 181, 191; 181, 192; 181, 220; 181, 239; 181, 240; 181, 261; 181, 284; 181, 318; 182, call; 182, 183; 182, 184; 183, identifier:isinstance; 184, argument_list; 184, 185; 184, 190; 185, attribute; 185, 186; 185, 189; 186, attribute; 186, 187; 186, 188; 187, identifier:self; 188, identifier:_intern; 189, identifier:value; 190, identifier:bool; 191, comment; 192, block; 192, 193; 192, 201; 192, 211; 192, 212; 193, expression_statement; 193, 194; 194, call; 194, 195; 194, 196; 195, identifier:print; 196, argument_list; 196, 197; 197, binary_operator:%; 197, 198; 197, 199; 198, string:'qvar = %r'; 199, tuple; 199, 200; 200, identifier:qvar; 201, expression_statement; 201, 202; 202, assignment; 202, 203; 202, 204; 203, identifier:new_val; 204, call; 204, 205; 204, 208; 205, attribute; 205, 206; 205, 207; 206, identifier:util_type; 207, identifier:smart_cast; 208, argument_list; 208, 209; 208, 210; 209, identifier:qvar; 210, identifier:bool; 211, comment; 212, expression_statement; 212, 213; 213, call; 213, 214; 213, 215; 214, identifier:print; 215, argument_list; 215, 216; 216, binary_operator:%; 216, 217; 216, 218; 217, string:'new_val = %r'; 218, tuple; 218, 219; 219, identifier:new_val; 220, elif_clause; 220, 221; 220, 230; 220, 231; 221, call; 221, 222; 221, 223; 222, identifier:isinstance; 223, argument_list; 223, 224; 223, 229; 224, attribute; 224, 225; 224, 228; 225, attribute; 225, 226; 225, 227; 226, identifier:self; 227, identifier:_intern; 228, identifier:value; 229, identifier:int; 230, comment; 231, block; 231, 232; 232, expression_statement; 232, 233; 233, assignment; 233, 234; 233, 235; 234, identifier:new_val; 235, call; 235, 236; 235, 237; 236, identifier:int; 237, argument_list; 237, 238; 238, identifier:qvar; 239, comment; 240, elif_clause; 240, 241; 240, 252; 240, 253; 241, comparison_operator:in; 241, 242; 241, 249; 242, call; 242, 243; 242, 248; 243, attribute; 243, 244; 243, 247; 244, attribute; 244, 245; 244, 246; 245, identifier:self; 246, identifier:_intern; 247, identifier:get_type; 248, argument_list; 249, attribute; 249, 250; 249, 251; 250, identifier:util_type; 251, identifier:VALID_FLOAT_TYPES; 252, comment; 253, block; 253, 254; 254, expression_statement; 254, 255; 255, assignment; 255, 256; 255, 257; 256, identifier:new_val; 257, call; 257, 258; 257, 259; 258, identifier:float; 259, argument_list; 259, 260; 260, identifier:qvar; 261, elif_clause; 261, 262; 261, 273; 261, 274; 262, call; 262, 263; 262, 264; 263, identifier:isinstance; 264, argument_list; 264, 265; 264, 270; 265, attribute; 265, 266; 265, 269; 266, attribute; 266, 267; 266, 268; 267, identifier:self; 268, identifier:_intern; 269, identifier:value; 270, attribute; 270, 271; 270, 272; 271, identifier:six; 272, identifier:string_types; 273, comment; 274, block; 274, 275; 275, expression_statement; 275, 276; 276, assignment; 276, 277; 276, 278; 277, identifier:new_val; 278, call; 278, 279; 278, 282; 279, attribute; 279, 280; 279, 281; 280, identifier:six; 281, identifier:text_type; 282, argument_list; 282, 283; 283, identifier:qvar; 284, elif_clause; 284, 285; 284, 294; 284, 295; 285, call; 285, 286; 285, 287; 286, identifier:isinstance; 287, argument_list; 287, 288; 287, 293; 288, attribute; 288, 289; 288, 292; 289, attribute; 289, 290; 289, 291; 290, identifier:self; 291, identifier:_intern; 292, identifier:value; 293, identifier:PrefChoice; 294, comment; 295, block; 295, 296; 295, 305; 296, expression_statement; 296, 297; 297, assignment; 297, 298; 297, 299; 298, identifier:new_val; 299, call; 299, 300; 299, 303; 300, attribute; 300, 301; 300, 302; 301, identifier:six; 302, identifier:text_type; 303, argument_list; 303, 304; 304, identifier:qvar; 305, if_statement; 305, 306; 305, 313; 306, comparison_operator:==; 306, 307; 306, 312; 307, call; 307, 308; 307, 311; 308, attribute; 308, 309; 308, 310; 309, identifier:new_val; 310, identifier:upper; 311, argument_list; 312, string:'NONE'; 313, block; 313, 314; 314, expression_statement; 314, 315; 315, assignment; 315, 316; 315, 317; 316, identifier:new_val; 317, None; 318, else_clause; 318, 319; 319, block; 319, 320; 320, try_statement; 320, 321; 320, 322; 320, 361; 321, comment; 322, block; 322, 323; 322, 333; 323, expression_statement; 323, 324; 324, assignment; 324, 325; 324, 326; 325, identifier:type_; 326, call; 326, 327; 326, 332; 327, attribute; 327, 328; 327, 331; 328, attribute; 328, 329; 328, 330; 329, identifier:self; 330, identifier:_intern; 331, identifier:get_type; 332, argument_list; 333, if_statement; 333, 334; 333, 337; 333, 350; 334, comparison_operator:is; 334, 335; 334, 336; 335, identifier:type_; 336, None; 337, block; 337, 338; 338, expression_statement; 338, 339; 339, assignment; 339, 340; 339, 341; 340, identifier:new_val; 341, call; 341, 342; 341, 343; 342, identifier:type_; 343, argument_list; 343, 344; 344, call; 344, 345; 344, 348; 345, attribute; 345, 346; 345, 347; 346, identifier:six; 347, identifier:text_type; 348, argument_list; 348, 349; 349, identifier:qvar; 350, else_clause; 350, 351; 351, block; 351, 352; 352, expression_statement; 352, 353; 353, assignment; 353, 354; 353, 355; 354, identifier:new_val; 355, call; 355, 356; 355, 359; 356, attribute; 356, 357; 356, 358; 357, identifier:six; 358, identifier:text_type; 359, argument_list; 359, 360; 360, identifier:qvar; 361, except_clause; 361, 362; 361, 363; 362, identifier:Exception; 363, block; 363, 364; 364, raise_statement; 364, 365; 365, call; 365, 366; 365, 367; 366, identifier:NotImplementedError; 367, argument_list; 367, 368; 367, 382; 368, binary_operator:%; 368, 369; 368, 374; 369, parenthesized_expression; 369, 370; 370, concatenated_string; 370, 371; 370, 372; 370, 373; 371, string:'[Pref.qtleaf] Unknown internal type. '; 372, string:'type(_intern.value) = %r, '; 373, string:'_intern.get_type() = %r, '; 374, call; 374, 375; 374, 376; 375, identifier:type; 376, argument_list; 376, 377; 377, attribute; 377, 378; 377, 381; 378, attribute; 378, 379; 378, 380; 379, identifier:self; 380, identifier:_intern; 381, identifier:value; 382, call; 382, 383; 382, 388; 383, attribute; 383, 384; 383, 387; 384, attribute; 384, 385; 384, 386; 385, identifier:self; 386, identifier:_intern; 387, identifier:get_type; 388, argument_list; 389, comment; 390, if_statement; 390, 391; 390, 398; 391, call; 391, 392; 391, 393; 392, identifier:isinstance; 393, argument_list; 393, 394; 393, 395; 394, identifier:new_val; 395, attribute; 395, 396; 395, 397; 396, identifier:six; 397, identifier:string_types; 398, block; 398, 399; 399, if_statement; 399, 400; 399, 407; 399, 412; 399, 425; 400, comparison_operator:==; 400, 401; 400, 406; 401, call; 401, 402; 401, 405; 402, attribute; 402, 403; 402, 404; 403, identifier:new_val; 404, identifier:lower; 405, argument_list; 406, string:'none'; 407, block; 407, 408; 408, expression_statement; 408, 409; 409, assignment; 409, 410; 409, 411; 410, identifier:new_val; 411, None; 412, elif_clause; 412, 413; 412, 420; 413, comparison_operator:==; 413, 414; 413, 419; 414, call; 414, 415; 414, 418; 415, attribute; 415, 416; 415, 417; 416, identifier:new_val; 417, identifier:lower; 418, argument_list; 419, string:'true'; 420, block; 420, 421; 421, expression_statement; 421, 422; 422, assignment; 422, 423; 422, 424; 423, identifier:new_val; 424, True; 425, elif_clause; 425, 426; 425, 433; 426, comparison_operator:==; 426, 427; 426, 432; 427, call; 427, 428; 427, 431; 428, attribute; 428, 429; 428, 430; 429, identifier:new_val; 430, identifier:lower; 431, argument_list; 432, string:'false'; 433, block; 433, 434; 434, expression_statement; 434, 435; 435, assignment; 435, 436; 435, 437; 436, identifier:new_val; 437, False; 438, comment; 439, if_statement; 439, 440; 439, 441; 440, identifier:VERBOSE_PREF; 441, block; 441, 442; 441, 447; 441, 454; 441, 464; 442, expression_statement; 442, 443; 443, call; 443, 444; 443, 445; 444, identifier:print; 445, argument_list; 445, 446; 446, string:'---'; 447, expression_statement; 447, 448; 448, call; 448, 449; 448, 450; 449, identifier:print; 450, argument_list; 450, 451; 451, binary_operator:%; 451, 452; 451, 453; 452, string:'[pref.qt_set_leaf_data] new_val=%r'; 453, identifier:new_val; 454, expression_statement; 454, 455; 455, call; 455, 456; 455, 457; 456, identifier:print; 457, argument_list; 457, 458; 458, binary_operator:%; 458, 459; 458, 460; 459, string:'[pref.qt_set_leaf_data] type(new_val)=%r'; 460, call; 460, 461; 460, 462; 461, identifier:type; 462, argument_list; 462, 463; 463, identifier:new_val; 464, expression_statement; 464, 465; 465, call; 465, 466; 465, 467; 466, identifier:print; 467, argument_list; 467, 468; 468, string:'L____ [pref.qt_set_leaf_data]'; 469, comment; 470, comment; 471, return_statement; 471, 472; 472, call; 472, 473; 472, 480; 473, attribute; 473, 474; 473, 479; 474, attribute; 474, 475; 474, 478; 475, attribute; 475, 476; 475, 477; 476, identifier:self; 477, identifier:_tree; 478, identifier:parent; 479, identifier:pref_update; 480, argument_list; 480, 481; 480, 486; 481, attribute; 481, 482; 481, 485; 482, attribute; 482, 483; 482, 484; 483, identifier:self; 484, identifier:_intern; 485, identifier:name; 486, identifier:new_val; 487, return_statement; 487, 488; 488, string:'PrefNotEditable'
def _qt_set_leaf_data(self, qvar): """ Sets backend data using QVariants """ if VERBOSE_PREF: print('') print('+--- [pref.qt_set_leaf_data]') print('[pref.qt_set_leaf_data] qvar = %r' % qvar) print('[pref.qt_set_leaf_data] _intern.name=%r' % self._intern.name) print('[pref.qt_set_leaf_data] _intern.type_=%r' % self._intern.get_type()) print('[pref.qt_set_leaf_data] type(_intern.value)=%r' % type(self._intern.value)) print('[pref.qt_set_leaf_data] _intern.value=%r' % self._intern.value) #print('[pref.qt_set_leaf_data] qvar.toString()=%s' % six.text_type(qvar.toString())) if self._tree.parent is None: raise Exception('[Pref.qtleaf] Cannot set root preference') if self.qt_is_editable(): new_val = '[Pref.qtleaf] BadThingsHappenedInPref' if self._intern.value == PrefNode: raise Exception('[Pref.qtleaf] Qt can only change leafs') elif self._intern.value is None: # None could be a number of types def cast_order(var, order=[bool, int, float, six.text_type]): for type_ in order: try: ret = type_(var) return ret except Exception: continue new_val = cast_order(six.text_type(qvar)) self._intern.get_type() if isinstance(self._intern.value, bool): #new_val = bool(qvar.toBool()) print('qvar = %r' % (qvar,)) new_val = util_type.smart_cast(qvar, bool) #new_val = bool(eval(qvar, {}, {})) print('new_val = %r' % (new_val,)) elif isinstance(self._intern.value, int): #new_val = int(qvar.toInt()[0]) new_val = int(qvar) # elif isinstance(self._intern.value, float): elif self._intern.get_type() in util_type.VALID_FLOAT_TYPES: #new_val = float(qvar.toDouble()[0]) new_val = float(qvar) elif isinstance(self._intern.value, six.string_types): #new_val = six.text_type(qvar.toString()) new_val = six.text_type(qvar) elif isinstance(self._intern.value, PrefChoice): #new_val = qvar.toString() new_val = six.text_type(qvar) if new_val.upper() == 'NONE': new_val = None else: try: #new_val = six.text_type(qvar.toString()) type_ = self._intern.get_type() if type_ is not None: new_val = type_(six.text_type(qvar)) else: new_val = six.text_type(qvar) except Exception: raise NotImplementedError( ('[Pref.qtleaf] Unknown internal type. ' 'type(_intern.value) = %r, ' '_intern.get_type() = %r, ') % type(self._intern.value), self._intern.get_type()) # Check for a set of None if isinstance(new_val, six.string_types): if new_val.lower() == 'none': new_val = None elif new_val.lower() == 'true': new_val = True elif new_val.lower() == 'false': new_val = False # save to disk after modifying data if VERBOSE_PREF: print('---') print('[pref.qt_set_leaf_data] new_val=%r' % new_val) print('[pref.qt_set_leaf_data] type(new_val)=%r' % type(new_val)) print('L____ [pref.qt_set_leaf_data]') # TODO Add ability to set a callback function when certain # preferences are changed. return self._tree.parent.pref_update(self._intern.name, new_val) return 'PrefNotEditable'
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 14; 2, function_name:inject_all_external_modules; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 4, identifier:self; 5, default_parameter; 5, 6; 5, 7; 6, identifier:classname; 7, None; 8, default_parameter; 8, 9; 8, 10; 9, identifier:allow_override; 10, string:'override+warn'; 11, default_parameter; 11, 12; 11, 13; 12, identifier:strict; 13, True; 14, block; 14, 15; 14, 17; 14, 18; 14, 31; 14, 32; 14, 33; 14, 37; 14, 75; 14, 93; 15, expression_statement; 15, 16; 16, comment; 17, comment; 18, if_statement; 18, 19; 18, 22; 19, comparison_operator:is; 19, 20; 19, 21; 20, identifier:classname; 21, None; 22, block; 22, 23; 23, expression_statement; 23, 24; 24, assignment; 24, 25; 24, 26; 25, identifier:classname; 26, attribute; 26, 27; 26, 30; 27, attribute; 27, 28; 27, 29; 28, identifier:self; 29, identifier:__class__; 30, identifier:__name__; 31, comment; 32, comment; 33, expression_statement; 33, 34; 34, assignment; 34, 35; 34, 36; 35, identifier:NEW; 36, True; 37, if_statement; 37, 38; 37, 39; 37, 54; 38, identifier:NEW; 39, block; 39, 40; 40, expression_statement; 40, 41; 41, assignment; 41, 42; 41, 43; 42, identifier:classkey_list; 43, list_comprehension; 43, 44; 43, 45; 43, 48; 44, identifier:key; 45, for_in_clause; 45, 46; 45, 47; 46, identifier:key; 47, identifier:__CLASSTYPE_ATTRIBUTES__; 48, if_clause; 48, 49; 49, comparison_operator:==; 49, 50; 49, 53; 50, subscript; 50, 51; 50, 52; 51, identifier:key; 52, integer:0; 53, identifier:classname; 54, else_clause; 54, 55; 55, block; 55, 56; 55, 63; 55, 64; 55, 65; 56, expression_statement; 56, 57; 57, assignment; 57, 58; 57, 59; 58, identifier:injected_modules; 59, call; 59, 60; 59, 61; 60, identifier:get_injected_modules; 61, argument_list; 61, 62; 62, identifier:classname; 63, comment; 64, comment; 65, expression_statement; 65, 66; 66, assignment; 66, 67; 66, 68; 67, identifier:classkey_list; 68, list_comprehension; 68, 69; 68, 72; 69, attribute; 69, 70; 69, 71; 70, identifier:module; 71, identifier:CLASS_INJECT_KEY; 72, for_in_clause; 72, 73; 72, 74; 73, identifier:module; 74, identifier:injected_modules; 75, for_statement; 75, 76; 75, 77; 75, 78; 76, identifier:classkey; 77, identifier:classkey_list; 78, block; 78, 79; 79, expression_statement; 79, 80; 80, call; 80, 81; 80, 82; 81, identifier:inject_instance; 82, argument_list; 82, 83; 82, 84; 82, 87; 82, 90; 83, identifier:self; 84, keyword_argument; 84, 85; 84, 86; 85, identifier:classkey; 86, identifier:classkey; 87, keyword_argument; 87, 88; 87, 89; 88, identifier:allow_override; 89, identifier:allow_override; 90, keyword_argument; 90, 91; 90, 92; 91, identifier:strict; 92, False; 93, for_statement; 93, 94; 93, 95; 93, 96; 94, identifier:classkey; 95, identifier:classkey_list; 96, block; 96, 97; 97, expression_statement; 97, 98; 98, call; 98, 99; 98, 100; 99, identifier:postinject_instance; 100, argument_list; 100, 101; 100, 102; 101, identifier:self; 102, keyword_argument; 102, 103; 102, 104; 103, identifier:classkey; 104, identifier:classkey
def inject_all_external_modules(self, classname=None, allow_override='override+warn', strict=True): """ dynamically injects registered module methods into a class instance FIXME: naming convention and use this in all places where this clas is used """ #import utool as ut if classname is None: classname = self.__class__.__name__ #import utool as ut #ut.embed() NEW = True if NEW: classkey_list = [key for key in __CLASSTYPE_ATTRIBUTES__ if key[0] == classname] else: injected_modules = get_injected_modules(classname) # the variable must be named CLASS_INJECT_KEY # and only one class can be specified per module. classkey_list = [module.CLASS_INJECT_KEY for module in injected_modules] for classkey in classkey_list: inject_instance( self, classkey=classkey, allow_override=allow_override, strict=False) for classkey in classkey_list: postinject_instance( self, classkey=classkey)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 27; 2, function_name:inject_func_as_method; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 3, 12; 3, 15; 3, 18; 3, 21; 3, 24; 4, identifier:self; 5, identifier:func; 6, default_parameter; 6, 7; 6, 8; 7, identifier:method_name; 8, None; 9, default_parameter; 9, 10; 9, 11; 10, identifier:class_; 11, None; 12, default_parameter; 12, 13; 12, 14; 13, identifier:allow_override; 14, False; 15, default_parameter; 15, 16; 15, 17; 16, identifier:allow_main; 17, False; 18, default_parameter; 18, 19; 18, 20; 19, identifier:verbose; 20, True; 21, default_parameter; 21, 22; 21, 23; 22, identifier:override; 23, None; 24, default_parameter; 24, 25; 24, 26; 25, identifier:force; 26, False; 27, block; 27, 28; 27, 30; 27, 40; 27, 52; 27, 63; 27, 72; 27, 73; 27, 74; 27, 86; 27, 87; 27, 248; 28, expression_statement; 28, 29; 29, comment; 30, if_statement; 30, 31; 30, 34; 30, 35; 31, comparison_operator:is; 31, 32; 31, 33; 32, identifier:override; 33, None; 34, comment; 35, block; 35, 36; 36, expression_statement; 36, 37; 37, assignment; 37, 38; 37, 39; 38, identifier:allow_override; 39, identifier:override; 40, if_statement; 40, 41; 40, 44; 41, comparison_operator:is; 41, 42; 41, 43; 42, identifier:method_name; 43, None; 44, block; 44, 45; 45, expression_statement; 45, 46; 46, assignment; 46, 47; 46, 48; 47, identifier:method_name; 48, call; 48, 49; 48, 50; 49, identifier:get_funcname; 50, argument_list; 50, 51; 51, identifier:func; 52, if_statement; 52, 53; 52, 54; 53, identifier:force; 54, block; 54, 55; 54, 59; 55, expression_statement; 55, 56; 56, assignment; 56, 57; 56, 58; 57, identifier:allow_override; 58, True; 59, expression_statement; 59, 60; 60, assignment; 60, 61; 60, 62; 61, identifier:allow_main; 62, True; 63, expression_statement; 63, 64; 64, assignment; 64, 65; 64, 66; 65, identifier:old_method; 66, call; 66, 67; 66, 68; 67, identifier:getattr; 68, argument_list; 68, 69; 68, 70; 68, 71; 69, identifier:self; 70, identifier:method_name; 71, None; 72, comment; 73, comment; 74, expression_statement; 74, 75; 75, assignment; 75, 76; 75, 77; 76, identifier:new_method; 77, call; 77, 78; 77, 81; 78, attribute; 78, 79; 78, 80; 79, identifier:func; 80, identifier:__get__; 81, argument_list; 81, 82; 81, 83; 82, identifier:self; 83, attribute; 83, 84; 83, 85; 84, identifier:self; 85, identifier:__class__; 86, comment; 87, if_statement; 87, 88; 87, 91; 88, comparison_operator:is; 88, 89; 88, 90; 89, identifier:old_method; 90, None; 91, block; 91, 92; 91, 99; 91, 106; 91, 146; 91, 245; 91, 246; 92, expression_statement; 92, 93; 93, assignment; 93, 94; 93, 95; 94, identifier:old_im_func; 95, call; 95, 96; 95, 97; 96, identifier:get_method_func; 97, argument_list; 97, 98; 98, identifier:old_method; 99, expression_statement; 99, 100; 100, assignment; 100, 101; 100, 102; 101, identifier:new_im_func; 102, call; 102, 103; 102, 104; 103, identifier:get_method_func; 104, argument_list; 104, 105; 105, identifier:new_method; 106, if_statement; 106, 107; 106, 132; 107, boolean_operator:and; 107, 108; 107, 114; 108, boolean_operator:and; 108, 109; 108, 111; 109, not_operator; 109, 110; 110, identifier:allow_main; 111, comparison_operator:is; 111, 112; 111, 113; 112, identifier:old_im_func; 113, None; 114, parenthesized_expression; 114, 115; 115, boolean_operator:and; 115, 116; 115, 124; 116, comparison_operator:!=; 116, 117; 116, 123; 117, subscript; 117, 118; 117, 122; 118, call; 118, 119; 118, 120; 119, identifier:get_funcglobals; 120, argument_list; 120, 121; 121, identifier:old_im_func; 122, string:'__name__'; 123, string:'__main__'; 124, comparison_operator:==; 124, 125; 124, 131; 125, subscript; 125, 126; 125, 130; 126, call; 126, 127; 126, 128; 127, identifier:get_funcglobals; 128, argument_list; 128, 129; 129, identifier:new_im_func; 130, string:'__name__'; 131, string:'__main__'; 132, block; 132, 133; 132, 145; 133, if_statement; 133, 134; 133, 137; 134, boolean_operator:or; 134, 135; 134, 136; 135, True; 136, identifier:VERBOSE_CLASS; 137, block; 137, 138; 138, expression_statement; 138, 139; 139, call; 139, 140; 139, 141; 140, identifier:print; 141, argument_list; 141, 142; 142, binary_operator:%; 142, 143; 142, 144; 143, string:'[util_class] skipping re-inject of %r from __main__'; 144, identifier:method_name; 145, return_statement; 146, if_statement; 146, 147; 146, 154; 146, 155; 146, 156; 146, 157; 146, 159; 146, 172; 146, 186; 147, boolean_operator:or; 147, 148; 147, 151; 148, comparison_operator:is; 148, 149; 148, 150; 149, identifier:old_method; 150, identifier:new_method; 151, comparison_operator:is; 151, 152; 151, 153; 152, identifier:old_im_func; 153, identifier:new_im_func; 154, comment; 155, comment; 156, comment; 157, block; 157, 158; 158, return_statement; 159, elif_clause; 159, 160; 159, 163; 160, comparison_operator:is; 160, 161; 160, 162; 161, identifier:allow_override; 162, False; 163, block; 163, 164; 164, raise_statement; 164, 165; 165, call; 165, 166; 165, 167; 166, identifier:AssertionError; 167, argument_list; 167, 168; 168, binary_operator:%; 168, 169; 168, 170; 169, string:'Overrides are not allowed. Already have method_name=%r'; 170, parenthesized_expression; 170, 171; 171, identifier:method_name; 172, elif_clause; 172, 173; 172, 176; 173, comparison_operator:==; 173, 174; 173, 175; 174, identifier:allow_override; 175, string:'warn'; 176, block; 176, 177; 176, 185; 177, expression_statement; 177, 178; 178, call; 178, 179; 178, 180; 179, identifier:print; 180, argument_list; 180, 181; 181, binary_operator:%; 181, 182; 181, 183; 182, string:'WARNING: Overrides are not allowed. Already have method_name=%r. Skipping'; 183, parenthesized_expression; 183, 184; 184, identifier:method_name; 185, return_statement; 186, elif_clause; 186, 187; 186, 190; 186, 191; 186, 192; 187, comparison_operator:==; 187, 188; 187, 189; 188, identifier:allow_override; 189, string:'override+warn'; 190, comment; 191, comment; 192, block; 192, 193; 192, 201; 192, 213; 192, 225; 192, 235; 193, expression_statement; 193, 194; 194, call; 194, 195; 194, 196; 195, identifier:print; 196, argument_list; 196, 197; 197, binary_operator:%; 197, 198; 197, 199; 198, string:'WARNING: Overrides are allowed, but dangerous. method_name=%r.'; 199, parenthesized_expression; 199, 200; 200, identifier:method_name; 201, expression_statement; 201, 202; 202, call; 202, 203; 202, 204; 203, identifier:print; 204, argument_list; 204, 205; 205, binary_operator:%; 205, 206; 205, 207; 206, string:'old_method = %r, im_func=%s'; 207, tuple; 207, 208; 207, 209; 208, identifier:old_method; 209, call; 209, 210; 209, 211; 210, identifier:str; 211, argument_list; 211, 212; 212, identifier:old_im_func; 213, expression_statement; 213, 214; 214, call; 214, 215; 214, 216; 215, identifier:print; 216, argument_list; 216, 217; 217, binary_operator:%; 217, 218; 217, 219; 218, string:'new_method = %r, im_func=%s'; 219, tuple; 219, 220; 219, 221; 220, identifier:new_method; 221, call; 221, 222; 221, 223; 222, identifier:str; 223, argument_list; 223, 224; 224, identifier:new_im_func; 225, expression_statement; 225, 226; 226, call; 226, 227; 226, 228; 227, identifier:print; 228, argument_list; 228, 229; 229, subscript; 229, 230; 229, 234; 230, call; 230, 231; 230, 232; 231, identifier:get_funcglobals; 232, argument_list; 232, 233; 233, identifier:old_im_func; 234, string:'__name__'; 235, expression_statement; 235, 236; 236, call; 236, 237; 236, 238; 237, identifier:print; 238, argument_list; 238, 239; 239, subscript; 239, 240; 239, 244; 240, call; 240, 241; 240, 242; 241, identifier:get_funcglobals; 242, argument_list; 242, 243; 243, identifier:new_im_func; 244, string:'__name__'; 245, comment; 246, delete_statement; 246, 247; 247, identifier:old_method; 248, expression_statement; 248, 249; 249, call; 249, 250; 249, 251; 250, identifier:setattr; 251, argument_list; 251, 252; 251, 253; 251, 254; 252, identifier:self; 253, identifier:method_name; 254, identifier:new_method
def inject_func_as_method(self, func, method_name=None, class_=None, allow_override=False, allow_main=False, verbose=True, override=None, force=False): """ Injects a function into an object as a method Wraps func as a bound method of self. Then injects func into self It is preferable to use make_class_method_decorator and inject_instance Args: self (object): class instance func : some function whos first arugment is a class instance method_name (str) : default=func.__name__, if specified renames the method class_ (type) : if func is an unbound method of this class References: http://stackoverflow.com/questions/1015307/python-bind-an-unbound-method """ if override is not None: # TODO depcirate allow_override allow_override = override if method_name is None: method_name = get_funcname(func) if force: allow_override = True allow_main = True old_method = getattr(self, method_name, None) # Bind function to the class instance #new_method = types.MethodType(func, self, self.__class__) new_method = func.__get__(self, self.__class__) #new_method = profile(func.__get__(self, self.__class__)) if old_method is not None: old_im_func = get_method_func(old_method) new_im_func = get_method_func(new_method) if not allow_main and old_im_func is not None and ( get_funcglobals(old_im_func)['__name__'] != '__main__' and get_funcglobals(new_im_func)['__name__'] == '__main__'): if True or VERBOSE_CLASS: print('[util_class] skipping re-inject of %r from __main__' % method_name) return if old_method is new_method or old_im_func is new_im_func: #if verbose and util_arg.NOT_QUIET: # print('WARNING: Skipping injecting the same function twice: %r' % new_method) #print('WARNING: Injecting the same function twice: %r' % new_method) return elif allow_override is False: raise AssertionError( 'Overrides are not allowed. Already have method_name=%r' % (method_name)) elif allow_override == 'warn': print( 'WARNING: Overrides are not allowed. Already have method_name=%r. Skipping' % (method_name)) return elif allow_override == 'override+warn': #import utool as ut #ut.embed() print('WARNING: Overrides are allowed, but dangerous. method_name=%r.' % (method_name)) print('old_method = %r, im_func=%s' % (old_method, str(old_im_func))) print('new_method = %r, im_func=%s' % (new_method, str(new_im_func))) print(get_funcglobals(old_im_func)['__name__']) print(get_funcglobals(new_im_func)['__name__']) # TODO: does this actually decrement the refcount enough? del old_method setattr(self, method_name, new_method)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 11; 2, function_name:reload_class; 3, parameters; 3, 4; 3, 5; 3, 8; 4, identifier:self; 5, default_parameter; 5, 6; 5, 7; 6, identifier:verbose; 7, True; 8, default_parameter; 8, 9; 8, 10; 9, identifier:reload_module; 10, True; 11, block; 11, 12; 11, 14; 11, 19; 11, 25; 11, 33; 12, expression_statement; 12, 13; 13, comment; 14, import_statement; 14, 15; 15, aliased_import; 15, 16; 15, 18; 16, dotted_name; 16, 17; 17, identifier:utool; 18, identifier:ut; 19, expression_statement; 19, 20; 20, assignment; 20, 21; 20, 22; 21, identifier:verbose; 22, boolean_operator:or; 22, 23; 22, 24; 23, identifier:verbose; 24, identifier:VERBOSE_CLASS; 25, expression_statement; 25, 26; 26, assignment; 26, 27; 26, 28; 27, identifier:classname; 28, attribute; 28, 29; 28, 32; 29, attribute; 29, 30; 29, 31; 30, identifier:self; 31, identifier:__class__; 32, identifier:__name__; 33, try_statement; 33, 34; 33, 391; 34, block; 34, 35; 34, 43; 34, 57; 34, 58; 34, 97; 34, 98; 34, 145; 34, 151; 34, 152; 34, 160; 34, 161; 34, 166; 34, 178; 34, 350; 34, 351; 34, 352; 35, expression_statement; 35, 36; 36, assignment; 36, 37; 36, 38; 37, identifier:modname; 38, attribute; 38, 39; 38, 42; 39, attribute; 39, 40; 39, 41; 40, identifier:self; 41, identifier:__class__; 42, identifier:__module__; 43, if_statement; 43, 44; 43, 45; 44, identifier:verbose; 45, block; 45, 46; 46, expression_statement; 46, 47; 47, call; 47, 48; 47, 49; 48, identifier:print; 49, argument_list; 49, 50; 50, binary_operator:+; 50, 51; 50, 56; 51, binary_operator:+; 51, 52; 51, 55; 52, binary_operator:+; 52, 53; 52, 54; 53, string:'[class] reloading '; 54, identifier:classname; 55, string:' from '; 56, identifier:modname; 57, comment; 58, if_statement; 58, 59; 58, 64; 58, 83; 59, call; 59, 60; 59, 61; 60, identifier:hasattr; 61, argument_list; 61, 62; 61, 63; 62, identifier:self; 63, string:'_on_reload'; 64, block; 64, 65; 64, 77; 65, if_statement; 65, 66; 65, 69; 66, comparison_operator:>; 66, 67; 66, 68; 67, identifier:verbose; 68, integer:1; 69, block; 69, 70; 70, expression_statement; 70, 71; 71, call; 71, 72; 71, 73; 72, identifier:print; 73, argument_list; 73, 74; 74, binary_operator:+; 74, 75; 74, 76; 75, string:'[class] calling _on_reload for '; 76, identifier:classname; 77, expression_statement; 77, 78; 78, call; 78, 79; 78, 82; 79, attribute; 79, 80; 79, 81; 80, identifier:self; 81, identifier:_on_reload; 82, argument_list; 83, elif_clause; 83, 84; 83, 87; 84, comparison_operator:>; 84, 85; 84, 86; 85, identifier:verbose; 86, integer:1; 87, block; 87, 88; 88, expression_statement; 88, 89; 89, call; 89, 90; 89, 91; 90, identifier:print; 91, argument_list; 91, 92; 92, binary_operator:+; 92, 93; 92, 96; 93, binary_operator:+; 93, 94; 93, 95; 94, string:'[class] '; 95, identifier:classname; 96, string:' does not have an _on_reload function'; 97, comment; 98, function_definition; 98, 99; 98, 100; 98, 105; 99, function_name:find_base_clases; 100, parameters; 100, 101; 100, 102; 101, identifier:_class; 102, default_parameter; 102, 103; 102, 104; 103, identifier:find_base_clases; 104, None; 105, block; 105, 106; 105, 110; 105, 131; 105, 143; 106, expression_statement; 106, 107; 107, assignment; 107, 108; 107, 109; 108, identifier:class_list; 109, list:[]; 110, for_statement; 110, 111; 110, 112; 110, 115; 111, identifier:_baseclass; 112, attribute; 112, 113; 112, 114; 113, identifier:_class; 114, identifier:__bases__; 115, block; 115, 116; 115, 124; 116, expression_statement; 116, 117; 117, assignment; 117, 118; 117, 119; 118, identifier:parents; 119, call; 119, 120; 119, 121; 120, identifier:find_base_clases; 121, argument_list; 121, 122; 121, 123; 122, identifier:_baseclass; 123, identifier:find_base_clases; 124, expression_statement; 124, 125; 125, call; 125, 126; 125, 129; 126, attribute; 126, 127; 126, 128; 127, identifier:class_list; 128, identifier:extend; 129, argument_list; 129, 130; 130, identifier:parents; 131, if_statement; 131, 132; 131, 135; 132, comparison_operator:is; 132, 133; 132, 134; 133, identifier:_class; 134, identifier:object; 135, block; 135, 136; 136, expression_statement; 136, 137; 137, call; 137, 138; 137, 141; 138, attribute; 138, 139; 138, 140; 139, identifier:class_list; 140, identifier:append; 141, argument_list; 141, 142; 142, identifier:_class; 143, return_statement; 143, 144; 144, identifier:class_list; 145, expression_statement; 145, 146; 146, assignment; 146, 147; 146, 148; 147, identifier:head_class; 148, attribute; 148, 149; 148, 150; 149, identifier:self; 150, identifier:__class__; 151, comment; 152, expression_statement; 152, 153; 153, assignment; 153, 154; 153, 155; 154, identifier:class_list; 155, call; 155, 156; 155, 157; 156, identifier:find_base_clases; 157, argument_list; 157, 158; 157, 159; 158, identifier:head_class; 159, identifier:find_base_clases; 160, comment; 161, expression_statement; 161, 162; 162, assignment; 162, 163; 162, 164; 163, identifier:ignore; 164, set; 164, 165; 165, identifier:HashComparable2; 166, expression_statement; 166, 167; 167, assignment; 167, 168; 167, 169; 168, identifier:class_list; 169, list_comprehension; 169, 170; 169, 171; 169, 174; 170, identifier:_class; 171, for_in_clause; 171, 172; 171, 173; 172, identifier:_class; 173, identifier:class_list; 174, if_clause; 174, 175; 175, comparison_operator:not; 175, 176; 175, 177; 176, identifier:_class; 177, identifier:ignore; 178, for_statement; 178, 179; 178, 180; 178, 181; 179, identifier:_class; 180, identifier:class_list; 181, block; 181, 182; 181, 200; 181, 250; 181, 330; 181, 331; 181, 341; 182, if_statement; 182, 183; 182, 184; 183, identifier:verbose; 184, block; 184, 185; 185, expression_statement; 185, 186; 186, call; 186, 187; 186, 188; 187, identifier:print; 188, argument_list; 188, 189; 189, binary_operator:+; 189, 190; 189, 197; 190, binary_operator:+; 190, 191; 190, 196; 191, binary_operator:+; 191, 192; 191, 193; 192, string:'[class] reloading parent '; 193, attribute; 193, 194; 193, 195; 194, identifier:_class; 195, identifier:__name__; 196, string:' from '; 197, attribute; 197, 198; 197, 199; 198, identifier:_class; 199, identifier:__module__; 200, if_statement; 200, 201; 200, 206; 200, 207; 200, 208; 200, 238; 201, comparison_operator:==; 201, 202; 201, 205; 202, attribute; 202, 203; 202, 204; 203, identifier:_class; 204, identifier:__module__; 205, string:'__main__'; 206, comment; 207, comment; 208, block; 208, 209; 208, 219; 208, 230; 209, expression_statement; 209, 210; 210, assignment; 210, 211; 210, 212; 211, identifier:main_module_; 212, subscript; 212, 213; 212, 216; 213, attribute; 213, 214; 213, 215; 214, identifier:sys; 215, identifier:modules; 216, attribute; 216, 217; 216, 218; 217, identifier:_class; 218, identifier:__module__; 219, expression_statement; 219, 220; 220, assignment; 220, 221; 220, 222; 221, identifier:main_modname; 222, call; 222, 223; 222, 226; 223, attribute; 223, 224; 223, 225; 224, identifier:ut; 225, identifier:get_modname_from_modpath; 226, argument_list; 226, 227; 227, attribute; 227, 228; 227, 229; 228, identifier:main_module_; 229, identifier:__file__; 230, expression_statement; 230, 231; 231, assignment; 231, 232; 231, 233; 232, identifier:module_; 233, subscript; 233, 234; 233, 237; 234, attribute; 234, 235; 234, 236; 235, identifier:sys; 236, identifier:modules; 237, identifier:main_modname; 238, else_clause; 238, 239; 239, block; 239, 240; 240, expression_statement; 240, 241; 241, assignment; 241, 242; 241, 243; 242, identifier:module_; 243, subscript; 243, 244; 243, 247; 244, attribute; 244, 245; 244, 246; 245, identifier:sys; 246, identifier:modules; 247, attribute; 247, 248; 247, 249; 248, identifier:_class; 249, identifier:__module__; 250, if_statement; 250, 251; 250, 256; 250, 269; 251, call; 251, 252; 251, 253; 252, identifier:hasattr; 253, argument_list; 253, 254; 253, 255; 254, identifier:module_; 255, string:'rrr'; 256, block; 256, 257; 257, if_statement; 257, 258; 257, 259; 258, identifier:reload_module; 259, block; 259, 260; 260, expression_statement; 260, 261; 261, call; 261, 262; 261, 265; 262, attribute; 262, 263; 262, 264; 263, identifier:module_; 264, identifier:rrr; 265, argument_list; 265, 266; 266, keyword_argument; 266, 267; 266, 268; 267, identifier:verbose; 268, identifier:verbose; 269, else_clause; 269, 270; 270, block; 270, 271; 271, if_statement; 271, 272; 271, 273; 272, identifier:reload_module; 273, block; 273, 274; 273, 277; 273, 291; 274, import_statement; 274, 275; 275, dotted_name; 275, 276; 276, identifier:imp; 277, if_statement; 277, 278; 277, 279; 278, identifier:verbose; 279, block; 279, 280; 280, expression_statement; 280, 281; 281, call; 281, 282; 281, 283; 282, identifier:print; 283, argument_list; 283, 284; 284, binary_operator:+; 284, 285; 284, 290; 285, binary_operator:+; 285, 286; 285, 287; 286, string:'[class] reloading '; 287, attribute; 287, 288; 287, 289; 288, identifier:_class; 289, identifier:__module__; 290, string:' with imp'; 291, try_statement; 291, 292; 291, 300; 292, block; 292, 293; 293, expression_statement; 293, 294; 294, call; 294, 295; 294, 298; 295, attribute; 295, 296; 295, 297; 296, identifier:imp; 297, identifier:reload; 298, argument_list; 298, 299; 299, identifier:module_; 300, except_clause; 300, 301; 300, 304; 301, tuple; 301, 302; 301, 303; 302, identifier:ImportError; 303, identifier:AttributeError; 304, block; 304, 305; 304, 316; 304, 317; 304, 318; 305, expression_statement; 305, 306; 306, call; 306, 307; 306, 308; 307, identifier:print; 308, argument_list; 308, 309; 309, binary_operator:+; 309, 310; 309, 315; 310, binary_operator:+; 310, 311; 310, 312; 311, string:'[class] fallback reloading '; 312, attribute; 312, 313; 312, 314; 313, identifier:_class; 314, identifier:__module__; 315, string:' with imp'; 316, comment; 317, comment; 318, expression_statement; 318, 319; 319, call; 319, 320; 319, 323; 320, attribute; 320, 321; 320, 322; 321, identifier:imp; 322, identifier:load_source; 323, argument_list; 323, 324; 323, 327; 324, attribute; 324, 325; 324, 326; 325, identifier:module_; 326, identifier:__name__; 327, attribute; 327, 328; 327, 329; 328, identifier:module_; 329, identifier:__file__; 330, comment; 331, expression_statement; 331, 332; 332, assignment; 332, 333; 332, 334; 333, identifier:_newclass; 334, call; 334, 335; 334, 336; 335, identifier:getattr; 336, argument_list; 336, 337; 336, 338; 337, identifier:module_; 338, attribute; 338, 339; 338, 340; 339, identifier:_class; 340, identifier:__name__; 341, expression_statement; 341, 342; 342, call; 342, 343; 342, 344; 343, identifier:reload_class_methods; 344, argument_list; 344, 345; 344, 346; 344, 347; 345, identifier:self; 346, identifier:_newclass; 347, keyword_argument; 347, 348; 347, 349; 348, identifier:verbose; 349, identifier:verbose; 350, comment; 351, comment; 352, if_statement; 352, 353; 352, 358; 352, 377; 353, call; 353, 354; 353, 355; 354, identifier:hasattr; 355, argument_list; 355, 356; 355, 357; 356, identifier:self; 357, string:'_initialize_self'; 358, block; 358, 359; 358, 371; 359, if_statement; 359, 360; 359, 363; 360, comparison_operator:>; 360, 361; 360, 362; 361, identifier:verbose; 362, integer:1; 363, block; 363, 364; 364, expression_statement; 364, 365; 365, call; 365, 366; 365, 367; 366, identifier:print; 367, argument_list; 367, 368; 368, binary_operator:+; 368, 369; 368, 370; 369, string:'[class] calling _initialize_self for '; 370, identifier:classname; 371, expression_statement; 371, 372; 372, call; 372, 373; 372, 376; 373, attribute; 373, 374; 373, 375; 374, identifier:self; 375, identifier:_initialize_self; 376, argument_list; 377, elif_clause; 377, 378; 377, 381; 378, comparison_operator:>; 378, 379; 378, 380; 379, identifier:verbose; 380, integer:1; 381, block; 381, 382; 382, expression_statement; 382, 383; 383, call; 383, 384; 383, 385; 384, identifier:print; 385, argument_list; 385, 386; 386, binary_operator:+; 386, 387; 386, 390; 387, binary_operator:+; 387, 388; 387, 389; 388, string:'[class] '; 389, identifier:classname; 390, string:' does not have an _initialize_self function'; 391, except_clause; 391, 392; 391, 396; 392, as_pattern; 392, 393; 392, 394; 393, identifier:Exception; 394, as_pattern_target; 394, 395; 395, identifier:ex; 396, block; 396, 397; 396, 413; 397, expression_statement; 397, 398; 398, call; 398, 399; 398, 402; 399, attribute; 399, 400; 399, 401; 400, identifier:ut; 401, identifier:printex; 402, argument_list; 402, 403; 402, 404; 402, 405; 403, identifier:ex; 404, string:'Error Reloading Class'; 405, keyword_argument; 405, 406; 405, 407; 406, identifier:keys; 407, list:[ 'modname', 'module', 'class_', 'class_list', 'self', ]; 407, 408; 407, 409; 407, 410; 407, 411; 407, 412; 408, string:'modname'; 409, string:'module'; 410, string:'class_'; 411, string:'class_list'; 412, string:'self'; 413, raise_statement
def reload_class(self, verbose=True, reload_module=True): """ special class reloading function This function is often injected as rrr of classes """ import utool as ut verbose = verbose or VERBOSE_CLASS classname = self.__class__.__name__ try: modname = self.__class__.__module__ if verbose: print('[class] reloading ' + classname + ' from ' + modname) # --HACK-- if hasattr(self, '_on_reload'): if verbose > 1: print('[class] calling _on_reload for ' + classname) self._on_reload() elif verbose > 1: print('[class] ' + classname + ' does not have an _on_reload function') # Do for all inheriting classes def find_base_clases(_class, find_base_clases=None): class_list = [] for _baseclass in _class.__bases__: parents = find_base_clases(_baseclass, find_base_clases) class_list.extend(parents) if _class is not object: class_list.append(_class) return class_list head_class = self.__class__ # Determine if parents need reloading class_list = find_base_clases(head_class, find_base_clases) # HACK ignore = {HashComparable2} class_list = [_class for _class in class_list if _class not in ignore] for _class in class_list: if verbose: print('[class] reloading parent ' + _class.__name__ + ' from ' + _class.__module__) if _class.__module__ == '__main__': # Attempt to find the module that is the main module # This may be very hacky and potentially break main_module_ = sys.modules[_class.__module__] main_modname = ut.get_modname_from_modpath(main_module_.__file__) module_ = sys.modules[main_modname] else: module_ = sys.modules[_class.__module__] if hasattr(module_, 'rrr'): if reload_module: module_.rrr(verbose=verbose) else: if reload_module: import imp if verbose: print('[class] reloading ' + _class.__module__ + ' with imp') try: imp.reload(module_) except (ImportError, AttributeError): print('[class] fallback reloading ' + _class.__module__ + ' with imp') # one last thing to try. probably used ut.import_module_from_fpath # when importing this module imp.load_source(module_.__name__, module_.__file__) # Reset class attributes _newclass = getattr(module_, _class.__name__) reload_class_methods(self, _newclass, verbose=verbose) # --HACK-- # TODO: handle injected definitions if hasattr(self, '_initialize_self'): if verbose > 1: print('[class] calling _initialize_self for ' + classname) self._initialize_self() elif verbose > 1: print('[class] ' + classname + ' does not have an _initialize_self function') except Exception as ex: ut.printex(ex, 'Error Reloading Class', keys=[ 'modname', 'module', 'class_', 'class_list', 'self', ]) raise
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 7; 2, function_name:avl_join; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:t1; 5, identifier:t2; 6, identifier:node; 7, block; 7, 8; 7, 10; 7, 21; 7, 201; 8, expression_statement; 8, 9; 9, comment; 10, if_statement; 10, 11; 10, 12; 11, identifier:DEBUG_JOIN; 12, block; 12, 13; 13, expression_statement; 13, 14; 14, call; 14, 15; 14, 16; 15, identifier:print; 16, argument_list; 16, 17; 17, binary_operator:%; 17, 18; 17, 19; 18, string:'-- JOIN node=%r'; 19, tuple; 19, 20; 20, identifier:node; 21, if_statement; 21, 22; 21, 29; 21, 42; 21, 65; 21, 87; 22, boolean_operator:and; 22, 23; 22, 26; 23, comparison_operator:is; 23, 24; 23, 25; 24, identifier:t1; 25, None; 26, comparison_operator:is; 26, 27; 26, 28; 27, identifier:t2; 28, None; 29, block; 29, 30; 29, 38; 30, if_statement; 30, 31; 30, 32; 31, identifier:DEBUG_JOIN; 32, block; 32, 33; 33, expression_statement; 33, 34; 34, call; 34, 35; 34, 36; 35, identifier:print; 36, argument_list; 36, 37; 37, string:'Join Case 1'; 38, expression_statement; 38, 39; 39, assignment; 39, 40; 39, 41; 40, identifier:top; 41, identifier:node; 42, elif_clause; 42, 43; 42, 46; 42, 47; 43, comparison_operator:is; 43, 44; 43, 45; 44, identifier:t1; 45, None; 46, comment; 47, block; 47, 48; 47, 56; 48, if_statement; 48, 49; 48, 50; 49, identifier:DEBUG_JOIN; 50, block; 50, 51; 51, expression_statement; 51, 52; 52, call; 52, 53; 52, 54; 53, identifier:print; 54, argument_list; 54, 55; 55, string:'Join Case 2'; 56, expression_statement; 56, 57; 57, assignment; 57, 58; 57, 59; 58, identifier:top; 59, call; 59, 60; 59, 61; 60, identifier:avl_insert_dir; 61, argument_list; 61, 62; 61, 63; 61, 64; 62, identifier:t2; 63, identifier:node; 64, integer:0; 65, elif_clause; 65, 66; 65, 69; 66, comparison_operator:is; 66, 67; 66, 68; 67, identifier:t2; 68, None; 69, block; 69, 70; 69, 78; 70, if_statement; 70, 71; 70, 72; 71, identifier:DEBUG_JOIN; 72, block; 72, 73; 73, expression_statement; 73, 74; 74, call; 74, 75; 74, 76; 75, identifier:print; 76, argument_list; 76, 77; 77, string:'Join Case 3'; 78, expression_statement; 78, 79; 79, assignment; 79, 80; 79, 81; 80, identifier:top; 81, call; 81, 82; 81, 83; 82, identifier:avl_insert_dir; 83, argument_list; 83, 84; 83, 85; 83, 86; 84, identifier:t1; 85, identifier:node; 86, integer:1; 87, else_clause; 87, 88; 88, block; 88, 89; 88, 96; 88, 103; 89, expression_statement; 89, 90; 90, assignment; 90, 91; 90, 92; 91, identifier:h1; 92, call; 92, 93; 92, 94; 93, identifier:height; 94, argument_list; 94, 95; 95, identifier:t1; 96, expression_statement; 96, 97; 97, assignment; 97, 98; 97, 99; 98, identifier:h2; 99, call; 99, 100; 99, 101; 100, identifier:height; 101, argument_list; 101, 102; 102, identifier:t2; 103, if_statement; 103, 104; 103, 109; 103, 137; 103, 180; 104, comparison_operator:>; 104, 105; 104, 106; 105, identifier:h1; 106, binary_operator:+; 106, 107; 106, 108; 107, identifier:h2; 108, integer:1; 109, block; 109, 110; 109, 118; 109, 128; 110, if_statement; 110, 111; 110, 112; 111, identifier:DEBUG_JOIN; 112, block; 112, 113; 113, expression_statement; 113, 114; 114, call; 114, 115; 114, 116; 115, identifier:print; 116, argument_list; 116, 117; 117, string:'Join Case 4'; 118, expression_statement; 118, 119; 119, assignment; 119, 120; 119, 121; 120, identifier:top; 121, call; 121, 122; 121, 123; 122, identifier:avl_join_dir_recursive; 123, argument_list; 123, 124; 123, 125; 123, 126; 123, 127; 124, identifier:t1; 125, identifier:t2; 126, identifier:node; 127, integer:1; 128, if_statement; 128, 129; 128, 130; 129, identifier:DEBUG_JOIN; 130, block; 130, 131; 131, expression_statement; 131, 132; 132, call; 132, 133; 132, 134; 133, identifier:ascii_tree; 134, argument_list; 134, 135; 134, 136; 135, identifier:t1; 136, string:'top'; 137, elif_clause; 137, 138; 137, 143; 138, comparison_operator:>; 138, 139; 138, 140; 139, identifier:h2; 140, binary_operator:+; 140, 141; 140, 142; 141, identifier:h1; 142, integer:1; 143, block; 143, 144; 143, 162; 143, 172; 144, if_statement; 144, 145; 144, 146; 145, identifier:DEBUG_JOIN; 146, block; 146, 147; 146, 152; 146, 157; 147, expression_statement; 147, 148; 148, call; 148, 149; 148, 150; 149, identifier:print; 150, argument_list; 150, 151; 151, string:'Join Case 5'; 152, expression_statement; 152, 153; 153, call; 153, 154; 153, 155; 154, identifier:ascii_tree; 155, argument_list; 155, 156; 156, identifier:t1; 157, expression_statement; 157, 158; 158, call; 158, 159; 158, 160; 159, identifier:ascii_tree; 160, argument_list; 160, 161; 161, identifier:t2; 162, expression_statement; 162, 163; 163, assignment; 163, 164; 163, 165; 164, identifier:top; 165, call; 165, 166; 165, 167; 166, identifier:avl_join_dir_recursive; 167, argument_list; 167, 168; 167, 169; 167, 170; 167, 171; 168, identifier:t1; 169, identifier:t2; 170, identifier:node; 171, integer:0; 172, if_statement; 172, 173; 172, 174; 173, identifier:DEBUG_JOIN; 174, block; 174, 175; 175, expression_statement; 175, 176; 176, call; 176, 177; 176, 178; 177, identifier:ascii_tree; 178, argument_list; 178, 179; 179, identifier:top; 180, else_clause; 180, 181; 181, block; 181, 182; 181, 190; 181, 191; 182, if_statement; 182, 183; 182, 184; 183, identifier:DEBUG_JOIN; 184, block; 184, 185; 185, expression_statement; 185, 186; 186, call; 186, 187; 186, 188; 187, identifier:print; 188, argument_list; 188, 189; 189, string:'Join Case 6'; 190, comment; 191, expression_statement; 191, 192; 192, assignment; 192, 193; 192, 194; 193, identifier:top; 194, call; 194, 195; 194, 196; 195, identifier:avl_new_top; 196, argument_list; 196, 197; 196, 198; 196, 199; 196, 200; 197, identifier:t1; 198, identifier:t2; 199, identifier:node; 200, integer:0; 201, return_statement; 201, 202; 202, identifier:top
def avl_join(t1, t2, node): """ Joins two trees `t1` and `t1` with an intermediate key-value pair CommandLine: python -m utool.experimental.euler_tour_tree_avl avl_join Example: >>> # DISABLE_DOCTEST >>> from utool.experimental.euler_tour_tree_avl import * # NOQA >>> self = EulerTourTree(['a', 'b', 'c', 'b', 'd', 'b', 'a']) >>> other = EulerTourTree(['E', 'F', 'G', 'F', 'E']) >>> node = Node(value='Q') >>> root = avl_join(self.root, other.root, node) >>> new = EulerTourTree(root=root) >>> print('new = %r' % (new,)) >>> ut.quit_if_noshow() >>> self.print_tree() >>> other.print_tree() >>> new.print_tree() Example: >>> # DISABLE_DOCTEST >>> from utool.experimental.euler_tour_tree_avl import * # NOQA >>> self = EulerTourTree(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K']) >>> other = EulerTourTree(['X']) >>> node = Node(value='Q') >>> root = avl_join(self.root, other.root, node) >>> new = EulerTourTree(root=root) >>> print('new = %r' % (new,)) >>> ut.quit_if_noshow() >>> ut.qtensure() >>> #self.show_nx(fnum=1) >>> #other.show_nx(fnum=2) >>> new.show_nx() Running Time: O(abs(r(t1) - r(t2))) O(abs(height(t1) - height(t2))) """ if DEBUG_JOIN: print('-- JOIN node=%r' % (node,)) if t1 is None and t2 is None: if DEBUG_JOIN: print('Join Case 1') top = node elif t1 is None: # FIXME keep track of count if possible if DEBUG_JOIN: print('Join Case 2') top = avl_insert_dir(t2, node, 0) elif t2 is None: if DEBUG_JOIN: print('Join Case 3') top = avl_insert_dir(t1, node, 1) else: h1 = height(t1) h2 = height(t2) if h1 > h2 + 1: if DEBUG_JOIN: print('Join Case 4') top = avl_join_dir_recursive(t1, t2, node, 1) if DEBUG_JOIN: ascii_tree(t1, 'top') elif h2 > h1 + 1: if DEBUG_JOIN: print('Join Case 5') ascii_tree(t1) ascii_tree(t2) top = avl_join_dir_recursive(t1, t2, node, 0) if DEBUG_JOIN: ascii_tree(top) else: if DEBUG_JOIN: print('Join Case 6') # Insert at the top of the tree top = avl_new_top(t1, t2, node, 0) return top
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:git_sequence_editor_squash; 3, parameters; 3, 4; 4, identifier:fpath; 5, block; 5, 6; 5, 8; 5, 9; 5, 14; 5, 23; 5, 24; 5, 29; 5, 30; 5, 31; 5, 32; 5, 33; 5, 34; 5, 35; 5, 36; 5, 40; 5, 44; 5, 48; 5, 106; 5, 302; 5, 311; 5, 338; 5, 339; 5, 340; 5, 345; 6, expression_statement; 6, 7; 7, comment; 8, comment; 9, import_statement; 9, 10; 10, aliased_import; 10, 11; 10, 13; 11, dotted_name; 11, 12; 12, identifier:utool; 13, identifier:ut; 14, expression_statement; 14, 15; 15, assignment; 15, 16; 15, 17; 16, identifier:text; 17, call; 17, 18; 17, 21; 18, attribute; 18, 19; 18, 20; 19, identifier:ut; 20, identifier:read_from; 21, argument_list; 21, 22; 22, identifier:fpath; 23, comment; 24, expression_statement; 24, 25; 25, call; 25, 26; 25, 27; 26, identifier:print; 27, argument_list; 27, 28; 28, identifier:text; 29, comment; 30, comment; 31, comment; 32, comment; 33, comment; 34, comment; 35, comment; 36, expression_statement; 36, 37; 37, assignment; 37, 38; 37, 39; 38, identifier:prev_msg; 39, None; 40, expression_statement; 40, 41; 41, assignment; 41, 42; 41, 43; 42, identifier:prev_dt; 43, None; 44, expression_statement; 44, 45; 45, assignment; 45, 46; 45, 47; 46, identifier:new_lines; 47, list:[]; 48, function_definition; 48, 49; 48, 50; 48, 52; 49, function_name:get_commit_date; 50, parameters; 50, 51; 51, identifier:hashid; 52, block; 52, 53; 52, 76; 52, 77; 52, 82; 52, 83; 52, 92; 52, 93; 52, 102; 52, 103; 52, 104; 53, expression_statement; 53, 54; 54, assignment; 54, 55; 54, 59; 55, pattern_list; 55, 56; 55, 57; 55, 58; 56, identifier:out; 57, identifier:err; 58, identifier:ret; 59, call; 59, 60; 59, 63; 60, attribute; 60, 61; 60, 62; 61, identifier:ut; 62, identifier:cmd; 63, argument_list; 63, 64; 63, 67; 63, 70; 63, 73; 64, binary_operator:+; 64, 65; 64, 66; 65, string:'git show -s --format=%ci '; 66, identifier:hashid; 67, keyword_argument; 67, 68; 67, 69; 68, identifier:verbose; 69, False; 70, keyword_argument; 70, 71; 70, 72; 71, identifier:quiet; 72, True; 73, keyword_argument; 73, 74; 73, 75; 74, identifier:pad_stdout; 75, False; 76, comment; 77, import_from_statement; 77, 78; 77, 80; 78, dotted_name; 78, 79; 79, identifier:dateutil; 80, dotted_name; 80, 81; 81, identifier:parser; 82, comment; 83, expression_statement; 83, 84; 84, assignment; 84, 85; 84, 86; 85, identifier:stamp; 86, call; 86, 87; 86, 90; 87, attribute; 87, 88; 87, 89; 88, identifier:out; 89, identifier:strip; 90, argument_list; 90, 91; 91, string:'\n'; 92, comment; 93, expression_statement; 93, 94; 94, assignment; 94, 95; 94, 96; 95, identifier:dt; 96, call; 96, 97; 96, 100; 97, attribute; 97, 98; 97, 99; 98, identifier:parser; 99, identifier:parse; 100, argument_list; 100, 101; 101, identifier:stamp; 102, comment; 103, comment; 104, return_statement; 104, 105; 105, identifier:dt; 106, for_statement; 106, 107; 106, 108; 106, 114; 107, identifier:line; 108, call; 108, 109; 108, 112; 109, attribute; 109, 110; 109, 111; 110, identifier:text; 111, identifier:split; 112, argument_list; 112, 113; 113, string:'\n'; 114, block; 114, 115; 114, 124; 114, 146; 114, 152; 114, 158; 114, 171; 114, 197; 114, 201; 114, 215; 114, 267; 114, 294; 114, 298; 115, expression_statement; 115, 116; 116, assignment; 116, 117; 116, 118; 117, identifier:commit_line; 118, call; 118, 119; 118, 122; 119, attribute; 119, 120; 119, 121; 120, identifier:line; 121, identifier:split; 122, argument_list; 122, 123; 123, string:' '; 124, if_statement; 124, 125; 124, 131; 125, comparison_operator:<; 125, 126; 125, 130; 126, call; 126, 127; 126, 128; 127, identifier:len; 128, argument_list; 128, 129; 129, identifier:commit_line; 130, integer:3; 131, block; 131, 132; 131, 136; 131, 140; 131, 145; 132, expression_statement; 132, 133; 133, assignment; 133, 134; 133, 135; 134, identifier:prev_msg; 135, None; 136, expression_statement; 136, 137; 137, assignment; 137, 138; 137, 139; 138, identifier:prev_dt; 139, None; 140, expression_statement; 140, 141; 141, augmented_assignment:+=; 141, 142; 141, 143; 142, identifier:new_lines; 143, list:[line]; 143, 144; 144, identifier:line; 145, continue_statement; 146, expression_statement; 146, 147; 147, assignment; 147, 148; 147, 149; 148, identifier:action; 149, subscript; 149, 150; 149, 151; 150, identifier:commit_line; 151, integer:0; 152, expression_statement; 152, 153; 153, assignment; 153, 154; 153, 155; 154, identifier:hashid; 155, subscript; 155, 156; 155, 157; 156, identifier:commit_line; 157, integer:1; 158, expression_statement; 158, 159; 159, assignment; 159, 160; 159, 161; 160, identifier:msg; 161, call; 161, 162; 161, 165; 162, attribute; 162, 163; 162, 164; 163, string:' '; 164, identifier:join; 165, argument_list; 165, 166; 166, subscript; 166, 167; 166, 168; 167, identifier:commit_line; 168, slice; 168, 169; 168, 170; 169, integer:2; 170, colon; 171, try_statement; 171, 172; 171, 180; 172, block; 172, 173; 173, expression_statement; 173, 174; 174, assignment; 174, 175; 174, 176; 175, identifier:dt; 176, call; 176, 177; 176, 178; 177, identifier:get_commit_date; 178, argument_list; 178, 179; 179, identifier:hashid; 180, except_clause; 180, 181; 180, 182; 181, identifier:ValueError; 182, block; 182, 183; 182, 187; 182, 191; 182, 196; 183, expression_statement; 183, 184; 184, assignment; 184, 185; 184, 186; 185, identifier:prev_msg; 186, None; 187, expression_statement; 187, 188; 188, assignment; 188, 189; 188, 190; 189, identifier:prev_dt; 190, None; 191, expression_statement; 191, 192; 192, augmented_assignment:+=; 192, 193; 192, 194; 193, identifier:new_lines; 194, list:[line]; 194, 195; 195, identifier:line; 196, continue_statement; 197, expression_statement; 197, 198; 198, assignment; 198, 199; 198, 200; 199, identifier:orig_msg; 200, identifier:msg; 201, expression_statement; 201, 202; 202, assignment; 202, 203; 202, 204; 203, identifier:can_squash; 204, boolean_operator:and; 204, 205; 204, 212; 205, boolean_operator:and; 205, 206; 205, 209; 206, comparison_operator:==; 206, 207; 206, 208; 207, identifier:action; 208, string:'pick'; 209, comparison_operator:==; 209, 210; 209, 211; 210, identifier:msg; 211, string:'wip'; 212, comparison_operator:==; 212, 213; 212, 214; 213, identifier:prev_msg; 214, string:'wip'; 215, if_statement; 215, 216; 215, 223; 216, boolean_operator:and; 216, 217; 216, 220; 217, comparison_operator:is; 217, 218; 217, 219; 218, identifier:prev_dt; 219, None; 220, comparison_operator:==; 220, 221; 220, 222; 221, identifier:prev_msg; 222, string:'wip'; 223, block; 223, 224; 223, 230; 223, 231; 223, 235; 223, 246; 223, 247; 223, 253; 224, expression_statement; 224, 225; 225, assignment; 225, 226; 225, 227; 226, identifier:tdelta; 227, binary_operator:-; 227, 228; 227, 229; 228, identifier:dt; 229, identifier:prev_dt; 230, comment; 231, expression_statement; 231, 232; 232, assignment; 232, 233; 232, 234; 233, identifier:threshold_minutes; 234, integer:45; 235, expression_statement; 235, 236; 236, assignment; 236, 237; 236, 238; 237, identifier:td_min; 238, parenthesized_expression; 238, 239; 239, binary_operator:/; 239, 240; 239, 245; 240, call; 240, 241; 240, 244; 241, attribute; 241, 242; 241, 243; 242, identifier:tdelta; 243, identifier:total_seconds; 244, argument_list; 245, float:60.; 246, comment; 247, expression_statement; 247, 248; 248, augmented_assignment:&=; 248, 249; 248, 250; 249, identifier:can_squash; 250, comparison_operator:<; 250, 251; 250, 252; 251, identifier:td_min; 252, identifier:threshold_minutes; 253, expression_statement; 253, 254; 254, assignment; 254, 255; 254, 256; 255, identifier:msg; 256, binary_operator:+; 256, 257; 256, 258; 257, identifier:msg; 258, binary_operator:%; 258, 259; 258, 260; 259, string:' -- tdelta=%r'; 260, tuple; 260, 261; 261, call; 261, 262; 261, 265; 262, attribute; 262, 263; 262, 264; 263, identifier:ut; 264, identifier:get_timedelta_str; 265, argument_list; 265, 266; 266, identifier:tdelta; 267, if_statement; 267, 268; 267, 269; 267, 287; 268, identifier:can_squash; 269, block; 269, 270; 269, 282; 270, expression_statement; 270, 271; 271, assignment; 271, 272; 271, 273; 272, identifier:new_line; 273, call; 273, 274; 273, 277; 274, attribute; 274, 275; 274, 276; 275, string:' '; 276, identifier:join; 277, argument_list; 277, 278; 278, list:['squash', hashid, msg]; 278, 279; 278, 280; 278, 281; 279, string:'squash'; 280, identifier:hashid; 281, identifier:msg; 282, expression_statement; 282, 283; 283, augmented_assignment:+=; 283, 284; 283, 285; 284, identifier:new_lines; 285, list:[new_line]; 285, 286; 286, identifier:new_line; 287, else_clause; 287, 288; 288, block; 288, 289; 289, expression_statement; 289, 290; 290, augmented_assignment:+=; 290, 291; 290, 292; 291, identifier:new_lines; 292, list:[line]; 292, 293; 293, identifier:line; 294, expression_statement; 294, 295; 295, assignment; 295, 296; 295, 297; 296, identifier:prev_msg; 297, identifier:orig_msg; 298, expression_statement; 298, 299; 299, assignment; 299, 300; 299, 301; 300, identifier:prev_dt; 301, identifier:dt; 302, expression_statement; 302, 303; 303, assignment; 303, 304; 303, 305; 304, identifier:new_text; 305, call; 305, 306; 305, 309; 306, attribute; 306, 307; 306, 308; 307, string:'\n'; 308, identifier:join; 309, argument_list; 309, 310; 310, identifier:new_lines; 311, function_definition; 311, 312; 311, 313; 311, 315; 312, function_name:get_commit_date; 313, parameters; 313, 314; 314, identifier:hashid; 315, block; 315, 316; 315, 330; 316, expression_statement; 316, 317; 317, assignment; 317, 318; 317, 319; 318, identifier:out; 319, call; 319, 320; 319, 323; 320, attribute; 320, 321; 320, 322; 321, identifier:ut; 322, identifier:cmd; 323, argument_list; 323, 324; 323, 327; 324, binary_operator:+; 324, 325; 324, 326; 325, string:'git show -s --format=%ci '; 326, identifier:hashid; 327, keyword_argument; 327, 328; 327, 329; 328, identifier:verbose; 329, False; 330, expression_statement; 330, 331; 331, call; 331, 332; 331, 333; 332, identifier:print; 333, argument_list; 333, 334; 334, binary_operator:%; 334, 335; 334, 336; 335, string:'out = %r'; 336, tuple; 336, 337; 337, identifier:out; 338, comment; 339, comment; 340, expression_statement; 340, 341; 341, call; 341, 342; 341, 343; 342, identifier:print; 343, argument_list; 343, 344; 344, identifier:new_text; 345, expression_statement; 345, 346; 346, call; 346, 347; 346, 350; 347, attribute; 347, 348; 347, 349; 348, identifier:ut; 349, identifier:write_to; 350, argument_list; 350, 351; 350, 352; 350, 353; 351, identifier:fpath; 352, identifier:new_text; 353, keyword_argument; 353, 354; 353, 355; 354, identifier:n; 355, None
def git_sequence_editor_squash(fpath): r""" squashes wip messages CommandLine: python -m utool.util_git --exec-git_sequence_editor_squash Example: >>> # DISABLE_DOCTEST >>> # SCRIPT >>> import utool as ut >>> from utool.util_git import * # NOQA >>> fpath = ut.get_argval('--fpath', str, default=None) >>> git_sequence_editor_squash(fpath) Ignore: text = ut.codeblock( ''' pick 852aa05 better doctest for tips pick 3c779b8 wip pick 02bc21d wip pick 1853828 Fixed root tablename pick 9d50233 doctest updates pick 66230a5 wip pick c612e98 wip pick b298598 Fixed tablename error pick 1120a87 wip pick f6c4838 wip pick 7f92575 wip ''') Ignore: def squash_consecutive_commits_with_same_message(): # http://stackoverflow.com/questions/8226278/git-alias-to-squash-all-commits-with-a-particular-commit-message # Can do interactively with this. Can it be done automatically and pay attention to # Timestamps etc? git rebase --interactive HEAD~40 --autosquash git rebase --interactive $(git merge-base HEAD master) --autosquash # Lookbehind correct version %s/\([a-z]* [a-z0-9]* wip\n\)\@<=pick \([a-z0-9]*\) wip/squash \2 wip/gc # THE FULL NON-INTERACTIVE AUTOSQUASH SCRIPT # TODO: Dont squash if there is a one hour timedelta between commits GIT_EDITOR="cat $1" GIT_SEQUENCE_EDITOR="python -m utool.util_git --exec-git_sequence_editor_squash \ --fpath $1" git rebase -i $(git rev-list HEAD | tail -n 1) --autosquash --no-verify GIT_EDITOR="cat $1" GIT_SEQUENCE_EDITOR="python -m utool.util_git --exec-git_sequence_editor_squash \ --fpath $1" git rebase -i HEAD~10 --autosquash --no-verify GIT_EDITOR="cat $1" GIT_SEQUENCE_EDITOR="python -m utool.util_git --exec-git_sequence_editor_squash \ --fpath $1" git rebase -i $(git merge-base HEAD master) --autosquash --no-verify # 14d778fa30a93f85c61f34d09eddb6d2cafd11e2 # c509a95d4468ebb61097bd9f4d302367424772a3 # b0ffc26011e33378ee30730c5e0ef1994bfe1a90 # GIT_SEQUENCE_EDITOR=<script> git rebase -i <params> # GIT_SEQUENCE_EDITOR="echo 'FOOBAR $1' " git rebase -i HEAD~40 --autosquash # git checkout master # git branch -D tmp # git checkout -b tmp # option to get the tail commit $(git rev-list HEAD | tail -n 1) # GIT_SEQUENCE_EDITOR="python -m utool.util_git --exec-git_sequence_editor_squash \ --fpath $1" git rebase -i HEAD~40 --autosquash # GIT_SEQUENCE_EDITOR="python -m utool.util_git --exec-git_sequence_editor_squash \ --fpath $1" git rebase -i HEAD~40 --autosquash --no-verify <params> """ # print(sys.argv) import utool as ut text = ut.read_from(fpath) # print('fpath = %r' % (fpath,)) print(text) # Doesnt work because of fixed witdth requirement # search = (ut.util_regex.positive_lookbehind('[a-z]* [a-z0-9]* wip\n') + 'pick ' + # ut.reponamed_field('hash', '[a-z0-9]*') + ' wip') # repl = ('squash ' + ut.bref_field('hash') + ' wip') # import re # new_text = re.sub(search, repl, text, flags=re.MULTILINE) # print(new_text) prev_msg = None prev_dt = None new_lines = [] def get_commit_date(hashid): out, err, ret = ut.cmd('git show -s --format=%ci ' + hashid, verbose=False, quiet=True, pad_stdout=False) # from datetime import datetime from dateutil import parser # print('out = %r' % (out,)) stamp = out.strip('\n') # print('stamp = %r' % (stamp,)) dt = parser.parse(stamp) # dt = datetime.strptime(stamp, '%Y-%m-%d %H:%M:%S %Z') # print('dt = %r' % (dt,)) return dt for line in text.split('\n'): commit_line = line.split(' ') if len(commit_line) < 3: prev_msg = None prev_dt = None new_lines += [line] continue action = commit_line[0] hashid = commit_line[1] msg = ' ' .join(commit_line[2:]) try: dt = get_commit_date(hashid) except ValueError: prev_msg = None prev_dt = None new_lines += [line] continue orig_msg = msg can_squash = action == 'pick' and msg == 'wip' and prev_msg == 'wip' if prev_dt is not None and prev_msg == 'wip': tdelta = dt - prev_dt # Only squash closely consecutive commits threshold_minutes = 45 td_min = (tdelta.total_seconds() / 60.) # print(tdelta) can_squash &= td_min < threshold_minutes msg = msg + ' -- tdelta=%r' % (ut.get_timedelta_str(tdelta),) if can_squash: new_line = ' ' .join(['squash', hashid, msg]) new_lines += [new_line] else: new_lines += [line] prev_msg = orig_msg prev_dt = dt new_text = '\n'.join(new_lines) def get_commit_date(hashid): out = ut.cmd('git show -s --format=%ci ' + hashid, verbose=False) print('out = %r' % (out,)) # print('Dry run') # ut.dump_autogen_code(fpath, new_text) print(new_text) ut.write_to(fpath, new_text, n=None)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 25; 2, function_name:build_proteintable; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 7; 3, 10; 3, 13; 3, 16; 3, 19; 3, 22; 4, identifier:pqdb; 5, identifier:headerfields; 6, identifier:mergecutoff; 7, default_parameter; 7, 8; 7, 9; 8, identifier:isobaric; 9, False; 10, default_parameter; 10, 11; 10, 12; 11, identifier:precursor; 12, False; 13, default_parameter; 13, 14; 13, 15; 14, identifier:probability; 15, False; 16, default_parameter; 16, 17; 16, 18; 17, identifier:fdr; 18, False; 19, default_parameter; 19, 20; 19, 21; 20, identifier:pep; 21, False; 22, default_parameter; 22, 23; 22, 24; 23, identifier:genecentric; 24, False; 25, block; 25, 26; 25, 28; 25, 56; 25, 65; 25, 77; 25, 89; 25, 101; 25, 113; 25, 125; 25, 139; 25, 154; 25, 162; 25, 171; 25, 178; 25, 189; 25, 205; 25, 232; 25, 312; 26, expression_statement; 26, 27; 27, comment; 28, expression_statement; 28, 29; 29, assignment; 29, 30; 29, 31; 30, identifier:pdmap; 31, call; 31, 32; 31, 33; 32, identifier:create_featuredata_map; 33, argument_list; 33, 34; 33, 35; 33, 38; 33, 43; 33, 48; 33, 53; 34, identifier:pqdb; 35, keyword_argument; 35, 36; 35, 37; 36, identifier:genecentric; 37, identifier:genecentric; 38, keyword_argument; 38, 39; 38, 40; 39, identifier:psm_fill_fun; 40, attribute; 40, 41; 40, 42; 41, identifier:pinfo; 42, identifier:add_psms_to_proteindata; 43, keyword_argument; 43, 44; 43, 45; 44, identifier:pgene_fill_fun; 45, attribute; 45, 46; 45, 47; 46, identifier:pinfo; 47, identifier:add_protgene_to_protdata; 48, keyword_argument; 48, 49; 48, 50; 49, identifier:count_fun; 50, attribute; 50, 51; 50, 52; 51, identifier:pinfo; 52, identifier:count_peps_psms; 53, keyword_argument; 53, 54; 53, 55; 54, identifier:get_uniques; 55, True; 56, expression_statement; 56, 57; 57, assignment; 57, 58; 57, 59; 58, identifier:empty_return; 59, lambda; 59, 60; 59, 64; 60, lambda_parameters; 60, 61; 60, 62; 60, 63; 61, identifier:x; 62, identifier:y; 63, identifier:z; 64, dictionary; 65, expression_statement; 65, 66; 66, assignment; 66, 67; 66, 68; 67, identifier:iso_fun; 68, subscript; 68, 69; 68, 76; 69, dictionary; 69, 70; 69, 73; 70, pair; 70, 71; 70, 72; 71, True; 72, identifier:get_isobaric_quant; 73, pair; 73, 74; 73, 75; 74, False; 75, identifier:empty_return; 76, identifier:isobaric; 77, expression_statement; 77, 78; 78, assignment; 78, 79; 78, 80; 79, identifier:ms1_fun; 80, subscript; 80, 81; 80, 88; 81, dictionary; 81, 82; 81, 85; 82, pair; 82, 83; 82, 84; 83, True; 84, identifier:get_precursor_quant; 85, pair; 85, 86; 85, 87; 86, False; 87, identifier:empty_return; 88, identifier:precursor; 89, expression_statement; 89, 90; 90, assignment; 90, 91; 90, 92; 91, identifier:prob_fun; 92, subscript; 92, 93; 92, 100; 93, dictionary; 93, 94; 93, 97; 94, pair; 94, 95; 94, 96; 95, True; 96, identifier:get_prot_probability; 97, pair; 97, 98; 97, 99; 98, False; 99, identifier:empty_return; 100, identifier:probability; 101, expression_statement; 101, 102; 102, assignment; 102, 103; 102, 104; 103, identifier:fdr_fun; 104, subscript; 104, 105; 104, 112; 105, dictionary; 105, 106; 105, 109; 106, pair; 106, 107; 106, 108; 107, True; 108, identifier:get_prot_fdr; 109, pair; 109, 110; 109, 111; 110, False; 111, identifier:empty_return; 112, identifier:fdr; 113, expression_statement; 113, 114; 114, assignment; 114, 115; 114, 116; 115, identifier:pep_fun; 116, subscript; 116, 117; 116, 124; 117, dictionary; 117, 118; 117, 121; 118, pair; 118, 119; 118, 120; 119, True; 120, identifier:get_prot_pep; 121, pair; 121, 122; 121, 123; 122, False; 123, identifier:empty_return; 124, identifier:pep; 125, expression_statement; 125, 126; 126, assignment; 126, 127; 126, 128; 127, identifier:pdata_fun; 128, subscript; 128, 129; 128, 136; 129, dictionary; 129, 130; 129, 133; 130, pair; 130, 131; 130, 132; 131, True; 132, identifier:get_protein_data_genecentric; 133, pair; 133, 134; 133, 135; 134, False; 135, identifier:get_protein_data; 136, comparison_operator:is; 136, 137; 136, 138; 137, identifier:genecentric; 138, False; 139, expression_statement; 139, 140; 140, assignment; 140, 141; 140, 144; 141, pattern_list; 141, 142; 141, 143; 142, identifier:protein_sql; 143, identifier:sqlfieldmap; 144, call; 144, 145; 144, 148; 145, attribute; 145, 146; 145, 147; 146, identifier:pqdb; 147, identifier:prepare_mergetable_sql; 148, argument_list; 148, 149; 148, 150; 148, 151; 148, 152; 148, 153; 149, identifier:precursor; 150, identifier:isobaric; 151, identifier:probability; 152, identifier:fdr; 153, identifier:pep; 154, expression_statement; 154, 155; 155, assignment; 155, 156; 155, 157; 156, identifier:accession_field; 157, subscript; 157, 158; 157, 161; 158, attribute; 158, 159; 158, 160; 159, identifier:prottabledata; 160, identifier:ACCESSIONS; 161, identifier:genecentric; 162, expression_statement; 162, 163; 163, assignment; 163, 164; 163, 165; 164, identifier:proteins; 165, call; 165, 166; 165, 169; 166, attribute; 166, 167; 166, 168; 167, identifier:pqdb; 168, identifier:get_merged_features; 169, argument_list; 169, 170; 170, identifier:protein_sql; 171, expression_statement; 171, 172; 172, assignment; 172, 173; 172, 174; 173, identifier:protein; 174, call; 174, 175; 174, 176; 175, identifier:next; 176, argument_list; 176, 177; 177, identifier:proteins; 178, expression_statement; 178, 179; 179, assignment; 179, 180; 179, 181; 180, identifier:outprotein; 181, dictionary; 181, 182; 182, pair; 182, 183; 182, 184; 183, identifier:accession_field; 184, subscript; 184, 185; 184, 186; 185, identifier:protein; 186, subscript; 186, 187; 186, 188; 187, identifier:sqlfieldmap; 188, string:'p_acc'; 189, expression_statement; 189, 190; 190, assignment; 190, 191; 190, 192; 191, identifier:check_prot; 192, dictionary_comprehension; 192, 193; 192, 196; 193, pair; 193, 194; 193, 195; 194, identifier:k; 195, identifier:v; 196, for_in_clause; 196, 197; 196, 200; 197, pattern_list; 197, 198; 197, 199; 198, identifier:k; 199, identifier:v; 200, call; 200, 201; 200, 204; 201, attribute; 201, 202; 201, 203; 202, identifier:outprotein; 203, identifier:items; 204, argument_list; 205, if_statement; 205, 206; 205, 215; 206, boolean_operator:or; 206, 207; 206, 209; 207, not_operator; 207, 208; 208, identifier:mergecutoff; 209, call; 209, 210; 209, 211; 210, identifier:protein_pool_fdr_cutoff; 211, argument_list; 211, 212; 211, 213; 211, 214; 212, identifier:protein; 213, identifier:sqlfieldmap; 214, identifier:mergecutoff; 215, block; 215, 216; 216, expression_statement; 216, 217; 217, call; 217, 218; 217, 219; 218, identifier:fill_mergefeature; 219, argument_list; 219, 220; 219, 221; 219, 222; 219, 223; 219, 224; 219, 225; 219, 226; 219, 227; 219, 228; 219, 229; 219, 230; 219, 231; 220, identifier:outprotein; 221, identifier:iso_fun; 222, identifier:ms1_fun; 223, identifier:prob_fun; 224, identifier:fdr_fun; 225, identifier:pep_fun; 226, identifier:pdata_fun; 227, identifier:protein; 228, identifier:sqlfieldmap; 229, identifier:headerfields; 230, identifier:pdmap; 231, identifier:accession_field; 232, for_statement; 232, 233; 232, 234; 232, 235; 233, identifier:protein; 234, identifier:proteins; 235, block; 235, 236; 235, 248; 235, 256; 235, 296; 236, if_statement; 236, 237; 236, 246; 237, boolean_operator:and; 237, 238; 237, 239; 238, identifier:mergecutoff; 239, not_operator; 239, 240; 240, call; 240, 241; 240, 242; 241, identifier:protein_pool_fdr_cutoff; 242, argument_list; 242, 243; 242, 244; 242, 245; 243, identifier:protein; 244, identifier:sqlfieldmap; 245, identifier:mergecutoff; 246, block; 246, 247; 247, continue_statement; 248, expression_statement; 248, 249; 249, assignment; 249, 250; 249, 251; 250, identifier:p_acc; 251, subscript; 251, 252; 251, 253; 252, identifier:protein; 253, subscript; 253, 254; 253, 255; 254, identifier:sqlfieldmap; 255, string:'p_acc'; 256, if_statement; 256, 257; 256, 262; 256, 263; 256, 264; 257, comparison_operator:!=; 257, 258; 257, 259; 258, identifier:p_acc; 259, subscript; 259, 260; 259, 261; 260, identifier:outprotein; 261, identifier:accession_field; 262, comment; 263, comment; 264, block; 264, 265; 264, 273; 264, 280; 265, if_statement; 265, 266; 265, 269; 266, comparison_operator:!=; 266, 267; 266, 268; 267, identifier:outprotein; 268, identifier:check_prot; 269, block; 269, 270; 270, expression_statement; 270, 271; 271, yield; 271, 272; 272, identifier:outprotein; 273, expression_statement; 273, 274; 274, assignment; 274, 275; 274, 276; 275, identifier:outprotein; 276, dictionary; 276, 277; 277, pair; 277, 278; 277, 279; 278, identifier:accession_field; 279, identifier:p_acc; 280, expression_statement; 280, 281; 281, assignment; 281, 282; 281, 283; 282, identifier:check_prot; 283, dictionary_comprehension; 283, 284; 283, 287; 284, pair; 284, 285; 284, 286; 285, identifier:k; 286, identifier:v; 287, for_in_clause; 287, 288; 287, 291; 288, pattern_list; 288, 289; 288, 290; 289, identifier:k; 290, identifier:v; 291, call; 291, 292; 291, 295; 292, attribute; 292, 293; 292, 294; 293, identifier:outprotein; 294, identifier:items; 295, argument_list; 296, expression_statement; 296, 297; 297, call; 297, 298; 297, 299; 298, identifier:fill_mergefeature; 299, argument_list; 299, 300; 299, 301; 299, 302; 299, 303; 299, 304; 299, 305; 299, 306; 299, 307; 299, 308; 299, 309; 299, 310; 299, 311; 300, identifier:outprotein; 301, identifier:iso_fun; 302, identifier:ms1_fun; 303, identifier:prob_fun; 304, identifier:fdr_fun; 305, identifier:pep_fun; 306, identifier:pdata_fun; 307, identifier:protein; 308, identifier:sqlfieldmap; 309, identifier:headerfields; 310, identifier:pdmap; 311, identifier:accession_field; 312, if_statement; 312, 313; 312, 316; 313, comparison_operator:!=; 313, 314; 313, 315; 314, identifier:outprotein; 315, identifier:check_prot; 316, block; 316, 317; 317, expression_statement; 317, 318; 318, yield; 318, 319; 319, identifier:outprotein
def build_proteintable(pqdb, headerfields, mergecutoff, isobaric=False, precursor=False, probability=False, fdr=False, pep=False, genecentric=False): """Fetches proteins and quants from joined lookup table, loops through them and when all of a protein's quants have been collected, yields the protein quant information.""" pdmap = create_featuredata_map(pqdb, genecentric=genecentric, psm_fill_fun=pinfo.add_psms_to_proteindata, pgene_fill_fun=pinfo.add_protgene_to_protdata, count_fun=pinfo.count_peps_psms, get_uniques=True) empty_return = lambda x, y, z: {} iso_fun = {True: get_isobaric_quant, False: empty_return}[isobaric] ms1_fun = {True: get_precursor_quant, False: empty_return}[precursor] prob_fun = {True: get_prot_probability, False: empty_return}[probability] fdr_fun = {True: get_prot_fdr, False: empty_return}[fdr] pep_fun = {True: get_prot_pep, False: empty_return}[pep] pdata_fun = {True: get_protein_data_genecentric, False: get_protein_data}[genecentric is not False] protein_sql, sqlfieldmap = pqdb.prepare_mergetable_sql(precursor, isobaric, probability, fdr, pep) accession_field = prottabledata.ACCESSIONS[genecentric] proteins = pqdb.get_merged_features(protein_sql) protein = next(proteins) outprotein = {accession_field: protein[sqlfieldmap['p_acc']]} check_prot = {k: v for k, v in outprotein.items()} if not mergecutoff or protein_pool_fdr_cutoff(protein, sqlfieldmap, mergecutoff): fill_mergefeature(outprotein, iso_fun, ms1_fun, prob_fun, fdr_fun, pep_fun, pdata_fun, protein, sqlfieldmap, headerfields, pdmap, accession_field) for protein in proteins: if mergecutoff and not protein_pool_fdr_cutoff(protein, sqlfieldmap, mergecutoff): continue p_acc = protein[sqlfieldmap['p_acc']] if p_acc != outprotein[accession_field]: # check if protein has been filled, otherwise do not output # sometimes proteins have NA in all fields if outprotein != check_prot: yield outprotein outprotein = {accession_field: p_acc} check_prot = {k: v for k, v in outprotein.items()} fill_mergefeature(outprotein, iso_fun, ms1_fun, prob_fun, fdr_fun, pep_fun, pdata_fun, protein, sqlfieldmap, headerfields, pdmap, accession_field) if outprotein != check_prot: yield outprotein
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 16; 2, function_name:start_logging; 3, parameters; 3, 4; 3, 7; 3, 10; 3, 13; 4, default_parameter; 4, 5; 4, 6; 5, identifier:log_fpath; 6, None; 7, default_parameter; 7, 8; 7, 9; 8, identifier:mode; 9, string:'a'; 10, default_parameter; 10, 11; 10, 12; 11, identifier:appname; 12, string:'default'; 13, default_parameter; 13, 14; 13, 15; 14, identifier:log_dir; 15, None; 16, block; 16, 17; 16, 19; 16, 21; 16, 23; 16, 25; 16, 27; 16, 29; 16, 37; 16, 38; 17, expression_statement; 17, 18; 18, comment; 19, global_statement; 19, 20; 20, identifier:__UTOOL_ROOT_LOGGER__; 21, global_statement; 21, 22; 22, identifier:__UTOOL_PRINT__; 23, global_statement; 23, 24; 24, identifier:__UTOOL_WRITE__; 25, global_statement; 25, 26; 26, identifier:__UTOOL_FLUSH__; 27, global_statement; 27, 28; 28, identifier:__CURRENT_LOG_FPATH__; 29, if_statement; 29, 30; 29, 31; 30, identifier:LOGGING_VERBOSE; 31, block; 31, 32; 32, expression_statement; 32, 33; 33, call; 33, 34; 33, 35; 34, identifier:print; 35, argument_list; 35, 36; 36, string:'[utool] start_logging()'; 37, comment; 38, if_statement; 38, 39; 38, 49; 38, 437; 39, boolean_operator:and; 39, 40; 39, 45; 40, boolean_operator:and; 40, 41; 40, 44; 41, comparison_operator:is; 41, 42; 41, 43; 42, identifier:__UTOOL_ROOT_LOGGER__; 43, None; 44, identifier:__IN_MAIN_PROCESS__; 45, not_operator; 45, 46; 46, call; 46, 47; 46, 48; 47, identifier:__inside_doctest; 48, argument_list; 49, block; 49, 50; 49, 58; 49, 59; 49, 79; 49, 83; 49, 84; 49, 103; 49, 104; 49, 113; 49, 120; 49, 121; 49, 122; 49, 134; 49, 135; 49, 142; 49, 148; 49, 149; 49, 150; 49, 158; 49, 166; 49, 172; 49, 181; 49, 182; 49, 205; 49, 245; 49, 382; 49, 408; 49, 409; 49, 413; 49, 417; 49, 421; 49, 422; 50, if_statement; 50, 51; 50, 52; 51, identifier:LOGGING_VERBOSE; 52, block; 52, 53; 53, expression_statement; 53, 54; 54, call; 54, 55; 54, 56; 55, identifier:print; 56, argument_list; 56, 57; 57, string:'[utool] start_logging()... rootcheck OK'; 58, comment; 59, if_statement; 59, 60; 59, 63; 60, comparison_operator:is; 60, 61; 60, 62; 61, identifier:log_fpath; 62, None; 63, block; 63, 64; 64, expression_statement; 64, 65; 65, assignment; 65, 66; 65, 67; 66, identifier:log_fpath; 67, call; 67, 68; 67, 69; 68, identifier:get_log_fpath; 69, argument_list; 69, 70; 69, 73; 69, 76; 70, keyword_argument; 70, 71; 70, 72; 71, identifier:num; 72, string:'next'; 73, keyword_argument; 73, 74; 73, 75; 74, identifier:appname; 75, identifier:appname; 76, keyword_argument; 76, 77; 76, 78; 77, identifier:log_dir; 78, identifier:log_dir; 79, expression_statement; 79, 80; 80, assignment; 80, 81; 80, 82; 81, identifier:__CURRENT_LOG_FPATH__; 82, identifier:log_fpath; 83, comment; 84, if_statement; 84, 85; 84, 88; 85, boolean_operator:or; 85, 86; 85, 87; 86, identifier:VERBOSE; 87, identifier:LOGGING_VERBOSE; 88, block; 88, 89; 88, 96; 89, expression_statement; 89, 90; 90, assignment; 90, 91; 90, 92; 91, identifier:startmsg; 92, parenthesized_expression; 92, 93; 93, binary_operator:%; 93, 94; 93, 95; 94, string:'logging to log_fpath=%r'; 95, identifier:log_fpath; 96, expression_statement; 96, 97; 97, call; 97, 98; 97, 101; 98, call; 98, 99; 98, 100; 99, identifier:_utool_print; 100, argument_list; 101, argument_list; 101, 102; 102, identifier:startmsg; 103, comment; 104, expression_statement; 104, 105; 105, assignment; 105, 106; 105, 107; 106, identifier:__UTOOL_ROOT_LOGGER__; 107, call; 107, 108; 107, 111; 108, attribute; 108, 109; 108, 110; 109, identifier:logging; 110, identifier:getLogger; 111, argument_list; 111, 112; 112, string:'root'; 113, expression_statement; 113, 114; 114, call; 114, 115; 114, 118; 115, attribute; 115, 116; 115, 117; 116, identifier:__UTOOL_ROOT_LOGGER__; 117, identifier:setLevel; 118, argument_list; 118, 119; 119, string:'DEBUG'; 120, comment; 121, comment; 122, expression_statement; 122, 123; 123, assignment; 123, 124; 123, 125; 124, identifier:logfile_handler; 125, call; 125, 126; 125, 129; 126, attribute; 126, 127; 126, 128; 127, identifier:logging; 128, identifier:FileHandler; 129, argument_list; 129, 130; 129, 131; 130, identifier:log_fpath; 131, keyword_argument; 131, 132; 131, 133; 132, identifier:mode; 133, identifier:mode; 134, comment; 135, expression_statement; 135, 136; 136, assignment; 136, 137; 136, 138; 137, identifier:stdout_handler; 138, call; 138, 139; 138, 140; 139, identifier:CustomStreamHandler; 140, argument_list; 140, 141; 141, identifier:__UTOOL_STDOUT__; 142, expression_statement; 142, 143; 143, assignment; 143, 144; 143, 147; 144, attribute; 144, 145; 144, 146; 145, identifier:stdout_handler; 146, identifier:terminator; 147, string:''; 148, comment; 149, comment; 150, expression_statement; 150, 151; 151, call; 151, 152; 151, 153; 152, identifier:add_logging_handler; 153, argument_list; 153, 154; 153, 155; 154, identifier:logfile_handler; 155, keyword_argument; 155, 156; 155, 157; 156, identifier:format_; 157, string:'file'; 158, expression_statement; 158, 159; 159, call; 159, 160; 159, 161; 160, identifier:add_logging_handler; 161, argument_list; 161, 162; 161, 163; 162, identifier:stdout_handler; 163, keyword_argument; 163, 164; 163, 165; 164, identifier:format_; 165, string:'stdout'; 166, expression_statement; 166, 167; 167, assignment; 167, 168; 167, 171; 168, attribute; 168, 169; 168, 170; 169, identifier:__UTOOL_ROOT_LOGGER__; 170, identifier:propagate; 171, False; 172, expression_statement; 172, 173; 173, call; 173, 174; 173, 177; 174, attribute; 174, 175; 174, 176; 175, identifier:__UTOOL_ROOT_LOGGER__; 176, identifier:setLevel; 177, argument_list; 177, 178; 178, attribute; 178, 179; 178, 180; 179, identifier:logging; 180, identifier:DEBUG; 181, comment; 182, function_definition; 182, 183; 182, 184; 182, 187; 183, function_name:utool_flush; 184, parameters; 184, 185; 185, list_splat_pattern; 185, 186; 186, identifier:args; 187, block; 187, 188; 187, 190; 187, 191; 187, 197; 187, 198; 187, 199; 187, 200; 187, 201; 187, 202; 187, 203; 187, 204; 188, expression_statement; 188, 189; 189, comment; 190, comment; 191, expression_statement; 191, 192; 192, call; 192, 193; 192, 196; 193, attribute; 193, 194; 193, 195; 194, identifier:stdout_handler; 195, identifier:flush; 196, argument_list; 197, comment; 198, comment; 199, comment; 200, comment; 201, comment; 202, comment; 203, comment; 204, comment; 205, function_definition; 205, 206; 205, 207; 205, 210; 206, function_name:utool_write; 207, parameters; 207, 208; 208, list_splat_pattern; 208, 209; 209, identifier:args; 210, block; 210, 211; 210, 213; 210, 214; 210, 215; 210, 230; 210, 231; 210, 238; 210, 239; 210, 240; 210, 241; 210, 242; 210, 243; 210, 244; 211, expression_statement; 211, 212; 212, comment; 213, comment; 214, comment; 215, expression_statement; 215, 216; 216, assignment; 216, 217; 216, 218; 217, identifier:msg; 218, call; 218, 219; 218, 222; 219, attribute; 219, 220; 219, 221; 220, string:', '; 221, identifier:join; 222, argument_list; 222, 223; 223, call; 223, 224; 223, 225; 224, identifier:map; 225, argument_list; 225, 226; 225, 229; 226, attribute; 226, 227; 226, 228; 227, identifier:six; 228, identifier:text_type; 229, identifier:args; 230, comment; 231, expression_statement; 231, 232; 232, call; 232, 233; 232, 236; 233, attribute; 233, 234; 233, 235; 234, identifier:__UTOOL_ROOT_LOGGER__; 235, identifier:info; 236, argument_list; 236, 237; 237, identifier:msg; 238, comment; 239, comment; 240, comment; 241, comment; 242, comment; 243, comment; 244, comment; 245, if_statement; 245, 246; 245, 248; 245, 316; 246, not_operator; 246, 247; 247, identifier:PRINT_ALL_CALLERS; 248, block; 248, 249; 249, function_definition; 249, 250; 249, 251; 249, 254; 250, function_name:utool_print; 251, parameters; 251, 252; 252, list_splat_pattern; 252, 253; 253, identifier:args; 254, block; 254, 255; 254, 257; 254, 258; 254, 262; 255, expression_statement; 255, 256; 256, comment; 257, comment; 258, expression_statement; 258, 259; 259, assignment; 259, 260; 259, 261; 260, identifier:endline; 261, string:'\n'; 262, try_statement; 262, 263; 262, 288; 263, block; 263, 264; 263, 279; 264, expression_statement; 264, 265; 265, assignment; 265, 266; 265, 267; 266, identifier:msg; 267, call; 267, 268; 267, 271; 268, attribute; 268, 269; 268, 270; 269, string:', '; 270, identifier:join; 271, argument_list; 271, 272; 272, call; 272, 273; 272, 274; 273, identifier:map; 274, argument_list; 274, 275; 274, 278; 275, attribute; 275, 276; 275, 277; 276, identifier:six; 277, identifier:text_type; 278, identifier:args; 279, return_statement; 279, 280; 280, call; 280, 281; 280, 284; 281, attribute; 281, 282; 281, 283; 282, identifier:__UTOOL_ROOT_LOGGER__; 283, identifier:info; 284, argument_list; 284, 285; 285, binary_operator:+; 285, 286; 285, 287; 286, identifier:msg; 287, identifier:endline; 288, except_clause; 288, 289; 288, 290; 289, identifier:UnicodeDecodeError; 290, block; 290, 291; 290, 306; 290, 307; 291, expression_statement; 291, 292; 292, assignment; 292, 293; 292, 294; 293, identifier:new_msg; 294, call; 294, 295; 294, 298; 295, attribute; 295, 296; 295, 297; 296, string:', '; 297, identifier:join; 298, argument_list; 298, 299; 299, call; 299, 300; 299, 301; 300, identifier:map; 301, argument_list; 301, 302; 301, 305; 302, attribute; 302, 303; 302, 304; 303, identifier:meta_util_six; 304, identifier:ensure_unicode; 305, identifier:args; 306, comment; 307, return_statement; 307, 308; 308, call; 308, 309; 308, 312; 309, attribute; 309, 310; 309, 311; 310, identifier:__UTOOL_ROOT_LOGGER__; 311, identifier:info; 312, argument_list; 312, 313; 313, binary_operator:+; 313, 314; 313, 315; 314, identifier:new_msg; 315, identifier:endline; 316, else_clause; 316, 317; 317, block; 317, 318; 318, function_definition; 318, 319; 318, 320; 318, 323; 319, function_name:utool_print; 320, parameters; 320, 321; 321, list_splat_pattern; 321, 322; 322, identifier:args; 323, block; 323, 324; 323, 326; 323, 331; 323, 335; 323, 339; 323, 346; 323, 362; 324, expression_statement; 324, 325; 325, comment; 326, import_statement; 326, 327; 327, aliased_import; 327, 328; 327, 330; 328, dotted_name; 328, 329; 329, identifier:utool; 330, identifier:ut; 331, expression_statement; 331, 332; 332, call; 332, 333; 332, 334; 333, identifier:utool_flush; 334, argument_list; 335, expression_statement; 335, 336; 336, assignment; 336, 337; 336, 338; 337, identifier:endline; 338, string:'\n'; 339, expression_statement; 339, 340; 340, call; 340, 341; 340, 344; 341, attribute; 341, 342; 341, 343; 342, identifier:__UTOOL_ROOT_LOGGER__; 343, identifier:info; 344, argument_list; 344, 345; 345, string:'\n\n----------'; 346, expression_statement; 346, 347; 347, call; 347, 348; 347, 351; 348, attribute; 348, 349; 348, 350; 349, identifier:__UTOOL_ROOT_LOGGER__; 350, identifier:info; 351, argument_list; 351, 352; 352, call; 352, 353; 352, 356; 353, attribute; 353, 354; 353, 355; 354, identifier:ut; 355, identifier:get_caller_name; 356, argument_list; 356, 357; 357, call; 357, 358; 357, 359; 358, identifier:range; 359, argument_list; 359, 360; 359, 361; 360, integer:0; 361, integer:20; 362, return_statement; 362, 363; 363, call; 363, 364; 363, 367; 364, attribute; 364, 365; 364, 366; 365, identifier:__UTOOL_ROOT_LOGGER__; 366, identifier:info; 367, argument_list; 367, 368; 368, binary_operator:+; 368, 369; 368, 381; 369, call; 369, 370; 369, 373; 370, attribute; 370, 371; 370, 372; 371, string:', '; 372, identifier:join; 373, argument_list; 373, 374; 374, call; 374, 375; 374, 376; 375, identifier:map; 376, argument_list; 376, 377; 376, 380; 377, attribute; 377, 378; 377, 379; 378, identifier:six; 379, identifier:text_type; 380, identifier:args; 381, identifier:endline; 382, function_definition; 382, 383; 382, 384; 382, 387; 383, function_name:utool_printdbg; 384, parameters; 384, 385; 385, list_splat_pattern; 385, 386; 386, identifier:args; 387, block; 387, 388; 387, 390; 388, expression_statement; 388, 389; 389, comment; 390, return_statement; 390, 391; 391, call; 391, 392; 391, 395; 392, attribute; 392, 393; 392, 394; 393, identifier:__UTOOL_ROOT_LOGGER__; 394, identifier:debug; 395, argument_list; 395, 396; 396, call; 396, 397; 396, 400; 397, attribute; 397, 398; 397, 399; 398, string:', '; 399, identifier:join; 400, argument_list; 400, 401; 401, call; 401, 402; 401, 403; 402, identifier:map; 403, argument_list; 403, 404; 403, 407; 404, attribute; 404, 405; 404, 406; 405, identifier:six; 406, identifier:text_type; 407, identifier:args; 408, comment; 409, expression_statement; 409, 410; 410, assignment; 410, 411; 410, 412; 411, identifier:__UTOOL_WRITE__; 412, identifier:utool_write; 413, expression_statement; 413, 414; 414, assignment; 414, 415; 414, 416; 415, identifier:__UTOOL_FLUSH__; 416, identifier:utool_flush; 417, expression_statement; 417, 418; 418, assignment; 418, 419; 418, 420; 419, identifier:__UTOOL_PRINT__; 420, identifier:utool_print; 421, comment; 422, if_statement; 422, 423; 422, 426; 423, boolean_operator:or; 423, 424; 423, 425; 424, identifier:VERBOSE; 425, identifier:LOGGING_VERBOSE; 426, block; 426, 427; 426, 432; 427, expression_statement; 427, 428; 428, call; 428, 429; 428, 430; 429, identifier:__UTOOL_PRINT__; 430, argument_list; 430, 431; 431, string:'<__LOG_START__>'; 432, expression_statement; 432, 433; 433, call; 433, 434; 433, 435; 434, identifier:__UTOOL_PRINT__; 435, argument_list; 435, 436; 436, identifier:startmsg; 437, else_clause; 437, 438; 438, block; 438, 439; 439, if_statement; 439, 440; 439, 441; 440, identifier:LOGGING_VERBOSE; 441, block; 441, 442; 441, 447; 441, 452; 441, 462; 441, 470; 442, expression_statement; 442, 443; 443, call; 443, 444; 443, 445; 444, identifier:print; 445, argument_list; 445, 446; 446, string:'[utool] start_logging()... FAILED TO START'; 447, expression_statement; 447, 448; 448, call; 448, 449; 448, 450; 449, identifier:print; 450, argument_list; 450, 451; 451, string:'DEBUG INFO'; 452, expression_statement; 452, 453; 453, call; 453, 454; 453, 455; 454, identifier:print; 455, argument_list; 455, 456; 456, binary_operator:%; 456, 457; 456, 458; 457, string:'__inside_doctest() = %r'; 458, tuple; 458, 459; 459, call; 459, 460; 459, 461; 460, identifier:__inside_doctest; 461, argument_list; 462, expression_statement; 462, 463; 463, call; 463, 464; 463, 465; 464, identifier:print; 465, argument_list; 465, 466; 466, binary_operator:%; 466, 467; 466, 468; 467, string:'__IN_MAIN_PROCESS__ = %r'; 468, tuple; 468, 469; 469, identifier:__IN_MAIN_PROCESS__; 470, expression_statement; 470, 471; 471, call; 471, 472; 471, 473; 472, identifier:print; 473, argument_list; 473, 474; 474, binary_operator:%; 474, 475; 474, 476; 475, string:'__UTOOL_ROOT_LOGGER__ = %r'; 476, tuple; 476, 477; 477, identifier:__UTOOL_ROOT_LOGGER__
def start_logging(log_fpath=None, mode='a', appname='default', log_dir=None): r""" Overwrites utool print functions to use a logger CommandLine: python -m utool.util_logging --test-start_logging:0 python -m utool.util_logging --test-start_logging:1 Example0: >>> # DISABLE_DOCTEST >>> import sys >>> sys.argv.append('--verb-logging') >>> import utool as ut >>> ut.start_logging() >>> ut.util_logging._utool_print()('hello world') >>> ut.util_logging._utool_write()('writing1') >>> ut.util_logging._utool_write()('writing2\n') >>> ut.util_logging._utool_write()('writing3') >>> ut.util_logging._utool_flush()() >>> handler = ut.util_logging.__UTOOL_ROOT_LOGGER__.handlers[0] >>> current_log_fpath = handler.stream.name >>> current_log_text = ut.read_from(current_log_fpath) >>> print('current_log_text =\n%s' % (current_log_text,)) >>> assert current_log_text.find('hello world') > 0, 'cant hello world' >>> assert current_log_text.find('writing1writing2') > 0, 'cant find writing1writing2' >>> assert current_log_text.find('writing3') > 0, 'cant find writing3' Example1: >>> # DISABLE_DOCTEST >>> # Ensure that progress is logged >>> import sys >>> sys.argv.append('--verb-logging') >>> import utool as ut >>> ut.start_logging() >>> [x for x in ut.ProgressIter(range(0, 1000), freq=4)] >>> handler = ut.util_logging.__UTOOL_ROOT_LOGGER__.handlers[0] >>> current_log_fpath = handler.stream.name >>> current_log_text = ut.read_from(current_log_fpath) >>> assert current_log_text.find('rate') > 0, 'progress was not logged' >>> print(current_log_text) """ global __UTOOL_ROOT_LOGGER__ global __UTOOL_PRINT__ global __UTOOL_WRITE__ global __UTOOL_FLUSH__ global __CURRENT_LOG_FPATH__ if LOGGING_VERBOSE: print('[utool] start_logging()') # FIXME: The test for doctest may not work if __UTOOL_ROOT_LOGGER__ is None and __IN_MAIN_PROCESS__ and not __inside_doctest(): if LOGGING_VERBOSE: print('[utool] start_logging()... rootcheck OK') #logging.config.dictConfig(LOGGING) if log_fpath is None: log_fpath = get_log_fpath(num='next', appname=appname, log_dir=log_dir) __CURRENT_LOG_FPATH__ = log_fpath # Print what is about to happen if VERBOSE or LOGGING_VERBOSE: startmsg = ('logging to log_fpath=%r' % log_fpath) _utool_print()(startmsg) # Create root logger __UTOOL_ROOT_LOGGER__ = logging.getLogger('root') __UTOOL_ROOT_LOGGER__.setLevel('DEBUG') # create file handler which logs even debug messages #fh = logging.handlers.WatchedFileHandler(log_fpath) logfile_handler = logging.FileHandler(log_fpath, mode=mode) #stdout_handler = logging.StreamHandler(__UTOOL_STDOUT__) stdout_handler = CustomStreamHandler(__UTOOL_STDOUT__) stdout_handler.terminator = '' # http://stackoverflow.com/questions/7168790/suppress-newline-in-python-logging-module #stdout_handler.terminator = '' add_logging_handler(logfile_handler, format_='file') add_logging_handler(stdout_handler, format_='stdout') __UTOOL_ROOT_LOGGER__.propagate = False __UTOOL_ROOT_LOGGER__.setLevel(logging.DEBUG) # Overwrite utool functions with the logging functions def utool_flush(*args): """ flushes whatever is in the current utool write buffer """ # Flushes only the stdout handler stdout_handler.flush() #__UTOOL_ROOT_LOGGER__.flush() #global __UTOOL_WRITE_BUFFER__ #if len(__UTOOL_WRITE_BUFFER__) > 0: # msg = ''.join(__UTOOL_WRITE_BUFFER__) # #sys.stdout.write('FLUSHING %r\n' % (len(__UTOOL_WRITE_BUFFER__))) # __UTOOL_WRITE_BUFFER__ = [] # return __UTOOL_ROOT_LOGGER__.info(msg) #__PYTHON_FLUSH__() def utool_write(*args): """ writes to current utool logs and to sys.stdout.write """ #global __UTOOL_WRITE_BUFFER__ #sys.stdout.write('WRITEING\n') msg = ', '.join(map(six.text_type, args)) #__UTOOL_WRITE_BUFFER__.append(msg) __UTOOL_ROOT_LOGGER__.info(msg) #if msg.endswith('\n'): # # Flush on newline, and remove newline # __UTOOL_WRITE_BUFFER__[-1] = __UTOOL_WRITE_BUFFER__[-1][:-1] # utool_flush() #elif len(__UTOOL_WRITE_BUFFER__) > 32: # # Flush if buffer is too large # utool_flush() if not PRINT_ALL_CALLERS: def utool_print(*args): """ standard utool print function """ #sys.stdout.write('PRINT\n') endline = '\n' try: msg = ', '.join(map(six.text_type, args)) return __UTOOL_ROOT_LOGGER__.info(msg + endline) except UnicodeDecodeError: new_msg = ', '.join(map(meta_util_six.ensure_unicode, args)) #print(new_msg) return __UTOOL_ROOT_LOGGER__.info(new_msg + endline) else: def utool_print(*args): """ debugging utool print function """ import utool as ut utool_flush() endline = '\n' __UTOOL_ROOT_LOGGER__.info('\n\n----------') __UTOOL_ROOT_LOGGER__.info(ut.get_caller_name(range(0, 20))) return __UTOOL_ROOT_LOGGER__.info(', '.join(map(six.text_type, args)) + endline) def utool_printdbg(*args): """ DRPRICATE standard utool print debug function """ return __UTOOL_ROOT_LOGGER__.debug(', '.join(map(six.text_type, args))) # overwrite the utool printers __UTOOL_WRITE__ = utool_write __UTOOL_FLUSH__ = utool_flush __UTOOL_PRINT__ = utool_print # Test out our shiney new logger if VERBOSE or LOGGING_VERBOSE: __UTOOL_PRINT__('<__LOG_START__>') __UTOOL_PRINT__(startmsg) else: if LOGGING_VERBOSE: print('[utool] start_logging()... FAILED TO START') print('DEBUG INFO') print('__inside_doctest() = %r' % (__inside_doctest(),)) print('__IN_MAIN_PROCESS__ = %r' % (__IN_MAIN_PROCESS__,)) print('__UTOOL_ROOT_LOGGER__ = %r' % (__UTOOL_ROOT_LOGGER__,))
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 9; 2, function_name:list_all_eq_to; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:list_; 5, identifier:val; 6, default_parameter; 6, 7; 6, 8; 7, identifier:strict; 8, True; 9, block; 9, 10; 9, 12; 9, 41; 10, expression_statement; 10, 11; 11, comment; 12, if_statement; 12, 13; 12, 24; 13, boolean_operator:and; 13, 14; 13, 17; 14, attribute; 14, 15; 14, 16; 15, identifier:util_type; 16, identifier:HAVE_NUMPY; 17, call; 17, 18; 17, 19; 18, identifier:isinstance; 19, argument_list; 19, 20; 19, 21; 20, identifier:val; 21, attribute; 21, 22; 21, 23; 22, identifier:np; 23, identifier:ndarray; 24, block; 24, 25; 25, return_statement; 25, 26; 26, call; 26, 27; 26, 28; 27, identifier:all; 28, argument_list; 28, 29; 29, list_comprehension; 29, 30; 29, 38; 30, call; 30, 31; 30, 34; 31, attribute; 31, 32; 31, 33; 32, identifier:np; 33, identifier:all; 34, argument_list; 34, 35; 35, comparison_operator:==; 35, 36; 35, 37; 36, identifier:item; 37, identifier:val; 38, for_in_clause; 38, 39; 38, 40; 39, identifier:item; 40, identifier:list_; 41, try_statement; 41, 42; 41, 43; 41, 44; 41, 96; 42, comment; 43, comment; 44, block; 44, 45; 44, 95; 45, with_statement; 45, 46; 45, 53; 46, with_clause; 46, 47; 47, with_item; 47, 48; 48, call; 48, 49; 48, 52; 49, attribute; 49, 50; 49, 51; 50, identifier:warnings; 51, identifier:catch_warnings; 52, argument_list; 53, block; 53, 54; 53, 64; 53, 74; 54, expression_statement; 54, 55; 55, call; 55, 56; 55, 59; 56, attribute; 56, 57; 56, 58; 57, identifier:warnings; 58, identifier:filterwarnings; 59, argument_list; 59, 60; 59, 61; 60, string:'ignore'; 61, keyword_argument; 61, 62; 61, 63; 62, identifier:category; 63, identifier:FutureWarning; 64, expression_statement; 64, 65; 65, assignment; 65, 66; 65, 67; 66, identifier:flags; 67, list_comprehension; 67, 68; 67, 71; 68, comparison_operator:==; 68, 69; 68, 70; 69, identifier:item; 70, identifier:val; 71, for_in_clause; 71, 72; 71, 73; 72, identifier:item; 73, identifier:list_; 74, return_statement; 74, 75; 75, call; 75, 76; 75, 77; 76, identifier:all; 77, argument_list; 77, 78; 78, list_comprehension; 78, 79; 78, 92; 79, conditional_expression:if; 79, 80; 79, 86; 79, 91; 80, call; 80, 81; 80, 84; 81, attribute; 81, 82; 81, 83; 82, identifier:np; 83, identifier:all; 84, argument_list; 84, 85; 85, identifier:flag; 86, call; 86, 87; 86, 88; 87, identifier:hasattr; 88, argument_list; 88, 89; 88, 90; 89, identifier:flag; 90, string:'__array__'; 91, identifier:flag; 92, for_in_clause; 92, 93; 92, 94; 93, identifier:flag; 94, identifier:flags; 95, comment; 96, except_clause; 96, 97; 96, 98; 97, identifier:ValueError; 98, block; 98, 99; 99, if_statement; 99, 100; 99, 102; 99, 120; 100, not_operator; 100, 101; 101, identifier:strict; 102, block; 102, 103; 103, return_statement; 103, 104; 104, call; 104, 105; 104, 106; 105, identifier:all; 106, argument_list; 106, 107; 107, list_comprehension; 107, 108; 107, 117; 108, comparison_operator:==; 108, 109; 108, 113; 109, call; 109, 110; 109, 111; 110, identifier:repr; 111, argument_list; 111, 112; 112, identifier:item; 113, call; 113, 114; 113, 115; 114, identifier:repr; 115, argument_list; 115, 116; 116, identifier:val; 117, for_in_clause; 117, 118; 117, 119; 118, identifier:item; 119, identifier:list_; 120, else_clause; 120, 121; 121, block; 121, 122; 122, raise_statement
def list_all_eq_to(list_, val, strict=True): """ checks to see if list is equal everywhere to a value Args: list_ (list): val : value to check against Returns: True if all items in the list are equal to val """ if util_type.HAVE_NUMPY and isinstance(val, np.ndarray): return all([np.all(item == val) for item in list_]) try: # FUTURE WARNING # FutureWarning: comparison to `None` will result in an elementwise object comparison in the future. with warnings.catch_warnings(): warnings.filterwarnings('ignore', category=FutureWarning) flags = [item == val for item in list_] return all([np.all(flag) if hasattr(flag, '__array__') else flag for flag in flags]) #return all([item == val for item in list_]) except ValueError: if not strict: return all([repr(item) == repr(val) for item in list_]) else: raise
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:isect; 3, parameters; 3, 4; 3, 5; 4, identifier:list1; 5, identifier:list2; 6, block; 6, 7; 6, 9; 6, 16; 7, expression_statement; 7, 8; 8, comment; 9, expression_statement; 9, 10; 10, assignment; 10, 11; 10, 12; 11, identifier:set2; 12, call; 12, 13; 12, 14; 13, identifier:set; 14, argument_list; 14, 15; 15, identifier:list2; 16, return_statement; 16, 17; 17, list_comprehension; 17, 18; 17, 19; 17, 22; 18, identifier:item; 19, for_in_clause; 19, 20; 19, 21; 20, identifier:item; 21, identifier:list1; 22, if_clause; 22, 23; 23, comparison_operator:in; 23, 24; 23, 25; 24, identifier:item; 25, identifier:set2
def isect(list1, list2): r""" returns list1 elements that are also in list2. preserves order of list1 intersect_ordered Args: list1 (list): list2 (list): Returns: list: new_list Example: >>> # DISABLE_DOCTEST >>> from utool.util_list import * # NOQA >>> list1 = ['featweight_rowid', 'feature_rowid', 'config_rowid', 'featweight_forground_weight'] >>> list2 = [u'featweight_rowid'] >>> result = intersect_ordered(list1, list2) >>> print(result) ['featweight_rowid'] Timeit: def timeit_func(func, *args): niter = 10 times = [] for count in range(niter): with ut.Timer(verbose=False) as t: _ = func(*args) times.append(t.ellapsed) return sum(times) / niter grid = { 'size1': [1000, 5000, 10000, 50000], 'size2': [1000, 5000, 10000, 50000], #'overlap': [0, 1], } data = [] for kw in ut.all_dict_combinations(grid): pool = np.arange(kw['size1'] * 2) size2 = size1 = kw['size1'] size2 = kw['size2'] list1 = (np.random.rand(size1) * size1).astype(np.int32).tolist() list1 = ut.random_sample(pool, size1).tolist() list2 = ut.random_sample(pool, size2).tolist() list1 = set(list1) list2 = set(list2) kw['ut'] = timeit_func(ut.isect, list1, list2) #kw['np1'] = timeit_func(np.intersect1d, list1, list2) #kw['py1'] = timeit_func(lambda a, b: set.intersection(set(a), set(b)), list1, list2) kw['py2'] = timeit_func(lambda a, b: sorted(set.intersection(set(a), set(b))), list1, list2) data.append(kw) import pandas as pd pd.options.display.max_rows = 1000 pd.options.display.width = 1000 df = pd.DataFrame.from_dict(data) data_keys = list(grid.keys()) other_keys = ut.setdiff(df.columns, data_keys) df = df.reindex_axis(data_keys + other_keys, axis=1) df['abs_change'] = df['ut'] - df['py2'] df['pct_change'] = df['abs_change'] / df['ut'] * 100 #print(df.sort('abs_change', ascending=False)) print(str(df).split('\n')[0]) for row in df.values: argmin = row[len(data_keys):len(data_keys) + len(other_keys)].argmin() + len(data_keys) print(' ' + ', '.join([ '%6d' % (r) if x < len(data_keys) else ( ut.color_text('%8.6f' % (r,), 'blue') if x == argmin else '%8.6f' % (r,)) for x, r in enumerate(row) ])) %timeit ut.isect(list1, list2) %timeit np.intersect1d(list1, list2, assume_unique=True) %timeit set.intersection(set(list1), set(list2)) #def highlight_max(s): # ''' # highlight the maximum in a Series yellow. # ''' # is_max = s == s.max() # return ['background-color: yellow' if v else '' for v in is_max] #df.style.apply(highlight_max) """ set2 = set(list2) return [item for item in list1 if item in set2]
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 8; 2, function_name:argsort; 3, parameters; 3, 4; 3, 6; 4, list_splat_pattern; 4, 5; 5, identifier:args; 6, dictionary_splat_pattern; 6, 7; 7, identifier:kwargs; 8, block; 8, 9; 8, 11; 9, expression_statement; 9, 10; 10, comment; 11, if_statement; 11, 12; 11, 26; 11, 61; 12, boolean_operator:and; 12, 13; 12, 19; 13, comparison_operator:==; 13, 14; 13, 18; 14, call; 14, 15; 14, 16; 15, identifier:len; 16, argument_list; 16, 17; 17, identifier:args; 18, integer:1; 19, call; 19, 20; 19, 21; 20, identifier:isinstance; 21, argument_list; 21, 22; 21, 25; 22, subscript; 22, 23; 22, 24; 23, identifier:args; 24, integer:0; 25, identifier:dict; 26, block; 26, 27; 26, 33; 26, 44; 26, 55; 27, expression_statement; 27, 28; 28, assignment; 28, 29; 28, 30; 29, identifier:dict_; 30, subscript; 30, 31; 30, 32; 31, identifier:args; 32, integer:0; 33, expression_statement; 33, 34; 34, assignment; 34, 35; 34, 36; 35, identifier:index_list; 36, call; 36, 37; 36, 38; 37, identifier:list; 38, argument_list; 38, 39; 39, call; 39, 40; 39, 43; 40, attribute; 40, 41; 40, 42; 41, identifier:dict_; 42, identifier:keys; 43, argument_list; 44, expression_statement; 44, 45; 45, assignment; 45, 46; 45, 47; 46, identifier:value_list; 47, call; 47, 48; 47, 49; 48, identifier:list; 49, argument_list; 49, 50; 50, call; 50, 51; 50, 54; 51, attribute; 51, 52; 51, 53; 52, identifier:dict_; 53, identifier:values; 54, argument_list; 55, return_statement; 55, 56; 56, call; 56, 57; 56, 58; 57, identifier:sortedby2; 58, argument_list; 58, 59; 58, 60; 59, identifier:index_list; 60, identifier:value_list; 61, else_clause; 61, 62; 62, block; 62, 63; 62, 78; 63, expression_statement; 63, 64; 64, assignment; 64, 65; 64, 66; 65, identifier:index_list; 66, call; 66, 67; 66, 68; 67, identifier:list; 68, argument_list; 68, 69; 69, call; 69, 70; 69, 71; 70, identifier:range; 71, argument_list; 71, 72; 72, call; 72, 73; 72, 74; 73, identifier:len; 74, argument_list; 74, 75; 75, subscript; 75, 76; 75, 77; 76, identifier:args; 77, integer:0; 78, return_statement; 78, 79; 79, call; 79, 80; 79, 81; 80, identifier:sortedby2; 81, argument_list; 81, 82; 81, 83; 81, 85; 82, identifier:index_list; 83, list_splat; 83, 84; 84, identifier:args; 85, dictionary_splat; 85, 86; 86, identifier:kwargs
def argsort(*args, **kwargs): """ like np.argsort but for lists Args: *args: multiple lists to sort by **kwargs: reverse (bool): sort order is descending if True else acscending CommandLine: python -m utool.util_list argsort Example: >>> # DISABLE_DOCTEST >>> from utool.util_list import * # NOQA >>> result = ut.argsort({'a': 3, 'b': 2, 'c': 100}) >>> print(result) """ if len(args) == 1 and isinstance(args[0], dict): dict_ = args[0] index_list = list(dict_.keys()) value_list = list(dict_.values()) return sortedby2(index_list, value_list) else: index_list = list(range(len(args[0]))) return sortedby2(index_list, *args, **kwargs)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 11; 2, function_name:argsort2; 3, parameters; 3, 4; 3, 5; 3, 8; 4, identifier:indexable; 5, default_parameter; 5, 6; 5, 7; 6, identifier:key; 7, None; 8, default_parameter; 8, 9; 8, 10; 9, identifier:reverse; 10, False; 11, block; 11, 12; 11, 14; 11, 15; 11, 55; 11, 56; 11, 106; 12, expression_statement; 12, 13; 13, comment; 14, comment; 15, if_statement; 15, 16; 15, 21; 15, 38; 16, call; 16, 17; 16, 18; 17, identifier:isinstance; 18, argument_list; 18, 19; 18, 20; 19, identifier:indexable; 20, identifier:dict; 21, block; 21, 22; 22, expression_statement; 22, 23; 23, assignment; 23, 24; 23, 25; 24, identifier:vk_iter; 25, generator_expression; 25, 26; 25, 29; 26, tuple; 26, 27; 26, 28; 27, identifier:v; 28, identifier:k; 29, for_in_clause; 29, 30; 29, 33; 30, pattern_list; 30, 31; 30, 32; 31, identifier:k; 32, identifier:v; 33, call; 33, 34; 33, 37; 34, attribute; 34, 35; 34, 36; 35, identifier:indexable; 36, identifier:items; 37, argument_list; 38, else_clause; 38, 39; 39, block; 39, 40; 40, expression_statement; 40, 41; 41, assignment; 41, 42; 41, 43; 42, identifier:vk_iter; 43, generator_expression; 43, 44; 43, 47; 44, tuple; 44, 45; 44, 46; 45, identifier:v; 46, identifier:k; 47, for_in_clause; 47, 48; 47, 51; 48, pattern_list; 48, 49; 48, 50; 49, identifier:k; 50, identifier:v; 51, call; 51, 52; 51, 53; 52, identifier:enumerate; 53, argument_list; 53, 54; 54, identifier:indexable; 55, comment; 56, if_statement; 56, 57; 56, 60; 56, 77; 57, comparison_operator:is; 57, 58; 57, 59; 58, identifier:key; 59, None; 60, block; 60, 61; 61, expression_statement; 61, 62; 62, assignment; 62, 63; 62, 64; 63, identifier:indices; 64, list_comprehension; 64, 65; 64, 66; 65, identifier:k; 66, for_in_clause; 66, 67; 66, 70; 67, pattern_list; 67, 68; 67, 69; 68, identifier:v; 69, identifier:k; 70, call; 70, 71; 70, 72; 71, identifier:sorted; 72, argument_list; 72, 73; 72, 74; 73, identifier:vk_iter; 74, keyword_argument; 74, 75; 74, 76; 75, identifier:reverse; 76, identifier:reverse; 77, else_clause; 77, 78; 78, block; 78, 79; 79, expression_statement; 79, 80; 80, assignment; 80, 81; 80, 82; 81, identifier:indices; 82, list_comprehension; 82, 83; 82, 84; 83, identifier:k; 84, for_in_clause; 84, 85; 84, 88; 85, pattern_list; 85, 86; 85, 87; 86, identifier:v; 87, identifier:k; 88, call; 88, 89; 88, 90; 89, identifier:sorted; 90, argument_list; 90, 91; 90, 92; 90, 103; 91, identifier:vk_iter; 92, keyword_argument; 92, 93; 92, 94; 93, identifier:key; 94, lambda; 94, 95; 94, 97; 95, lambda_parameters; 95, 96; 96, identifier:vk; 97, call; 97, 98; 97, 99; 98, identifier:key; 99, argument_list; 99, 100; 100, subscript; 100, 101; 100, 102; 101, identifier:vk; 102, integer:0; 103, keyword_argument; 103, 104; 103, 105; 104, identifier:reverse; 105, identifier:reverse; 106, return_statement; 106, 107; 107, identifier:indices
def argsort2(indexable, key=None, reverse=False): """ Returns the indices that would sort a indexable object. This is similar to np.argsort, but it is written in pure python and works on both lists and dictionaries. Args: indexable (list or dict): indexable to sort by Returns: list: indices: list of indices such that sorts the indexable Example: >>> # DISABLE_DOCTEST >>> import utool as ut >>> # argsort works on dicts >>> dict_ = indexable = {'a': 3, 'b': 2, 'c': 100} >>> indices = ut.argsort2(indexable) >>> assert list(ut.take(dict_, indices)) == sorted(dict_.values()) >>> # argsort works on lists >>> indexable = [100, 2, 432, 10] >>> indices = ut.argsort2(indexable) >>> assert list(ut.take(indexable, indices)) == sorted(indexable) >>> # argsort works on iterators >>> indexable = reversed(range(100)) >>> indices = ut.argsort2(indexable) >>> assert indices[0] == 99 """ # Create an iterator of value/key pairs if isinstance(indexable, dict): vk_iter = ((v, k) for k, v in indexable.items()) else: vk_iter = ((v, k) for k, v in enumerate(indexable)) # Sort by values and extract the keys if key is None: indices = [k for v, k in sorted(vk_iter, reverse=reverse)] else: indices = [k for v, k in sorted(vk_iter, key=lambda vk: key(vk[0]), reverse=reverse)] return indices
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 10; 2, function_name:issorted; 3, parameters; 3, 4; 3, 5; 4, identifier:list_; 5, default_parameter; 5, 6; 5, 7; 6, identifier:op; 7, attribute; 7, 8; 7, 9; 8, identifier:operator; 9, identifier:le; 10, block; 10, 11; 10, 13; 11, expression_statement; 11, 12; 12, comment; 13, return_statement; 13, 14; 14, call; 14, 15; 14, 16; 15, identifier:all; 16, generator_expression; 16, 17; 16, 28; 17, call; 17, 18; 17, 19; 18, identifier:op; 19, argument_list; 19, 20; 19, 23; 20, subscript; 20, 21; 20, 22; 21, identifier:list_; 22, identifier:ix; 23, subscript; 23, 24; 23, 25; 24, identifier:list_; 25, binary_operator:+; 25, 26; 25, 27; 26, identifier:ix; 27, integer:1; 28, for_in_clause; 28, 29; 28, 30; 29, identifier:ix; 30, call; 30, 31; 30, 32; 31, identifier:range; 32, argument_list; 32, 33; 33, binary_operator:-; 33, 34; 33, 38; 34, call; 34, 35; 34, 36; 35, identifier:len; 36, argument_list; 36, 37; 37, identifier:list_; 38, integer:1
def issorted(list_, op=operator.le): """ Determines if a list is sorted Args: list_ (list): op (func): sorted operation (default=operator.le) Returns: bool : True if the list is sorted """ return all(op(list_[ix], list_[ix + 1]) for ix in range(len(list_) - 1))
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 17; 2, function_name:depth_profile; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 3, 14; 4, identifier:list_; 5, default_parameter; 5, 6; 5, 7; 6, identifier:max_depth; 7, None; 8, default_parameter; 8, 9; 8, 10; 9, identifier:compress_homogenous; 10, True; 11, default_parameter; 11, 12; 11, 13; 12, identifier:compress_consecutive; 13, False; 14, default_parameter; 14, 15; 14, 16; 15, identifier:new_depth; 16, False; 17, block; 17, 18; 17, 20; 17, 39; 17, 43; 17, 44; 17, 62; 17, 178; 17, 232; 17, 379; 18, expression_statement; 18, 19; 19, comment; 20, if_statement; 20, 21; 20, 26; 21, call; 21, 22; 21, 23; 22, identifier:isinstance; 23, argument_list; 23, 24; 23, 25; 24, identifier:list_; 25, identifier:dict; 26, block; 26, 27; 26, 38; 27, expression_statement; 27, 28; 28, assignment; 28, 29; 28, 30; 29, identifier:list_; 30, call; 30, 31; 30, 32; 31, identifier:list; 32, argument_list; 32, 33; 33, call; 33, 34; 33, 37; 34, attribute; 34, 35; 34, 36; 35, identifier:list_; 36, identifier:values; 37, argument_list; 38, comment; 39, expression_statement; 39, 40; 40, assignment; 40, 41; 40, 42; 41, identifier:level_shape_list; 42, list:[]; 43, comment; 44, if_statement; 44, 45; 44, 56; 45, not_operator; 45, 46; 46, call; 46, 47; 46, 48; 47, identifier:any; 48, argument_list; 48, 49; 49, call; 49, 50; 49, 51; 50, identifier:map; 51, argument_list; 51, 52; 51, 55; 52, attribute; 52, 53; 52, 54; 53, identifier:util_type; 54, identifier:is_listlike; 55, identifier:list_; 56, block; 56, 57; 57, return_statement; 57, 58; 58, call; 58, 59; 58, 60; 59, identifier:len; 60, argument_list; 60, 61; 61, identifier:list_; 62, if_statement; 62, 63; 62, 66; 62, 85; 63, boolean_operator:and; 63, 64; 63, 65; 64, False; 65, identifier:new_depth; 66, block; 66, 67; 66, 68; 66, 69; 66, 70; 66, 71; 66, 72; 66, 73; 66, 74; 66, 75; 66, 76; 66, 77; 66, 78; 66, 79; 66, 80; 66, 81; 66, 82; 66, 83; 66, 84; 67, pass_statement; 68, comment; 69, comment; 70, comment; 71, comment; 72, comment; 73, comment; 74, comment; 75, comment; 76, comment; 77, comment; 78, comment; 79, comment; 80, comment; 81, comment; 82, comment; 83, comment; 84, comment; 85, else_clause; 85, 86; 86, block; 86, 87; 87, for_statement; 87, 88; 87, 89; 87, 90; 88, identifier:item; 89, identifier:list_; 90, block; 90, 91; 90, 110; 91, if_statement; 91, 92; 91, 97; 92, call; 92, 93; 92, 94; 93, identifier:isinstance; 94, argument_list; 94, 95; 94, 96; 95, identifier:item; 96, identifier:dict; 97, block; 97, 98; 97, 109; 98, expression_statement; 98, 99; 99, assignment; 99, 100; 99, 101; 100, identifier:item; 101, call; 101, 102; 101, 103; 102, identifier:list; 103, argument_list; 103, 104; 104, call; 104, 105; 104, 108; 105, attribute; 105, 106; 105, 107; 106, identifier:item; 107, identifier:values; 108, argument_list; 109, comment; 110, if_statement; 110, 111; 110, 117; 110, 169; 111, call; 111, 112; 111, 115; 112, attribute; 112, 113; 112, 114; 113, identifier:util_type; 114, identifier:is_listlike; 115, argument_list; 115, 116; 116, identifier:item; 117, block; 117, 118; 118, if_statement; 118, 119; 118, 122; 118, 134; 119, comparison_operator:is; 119, 120; 119, 121; 120, identifier:max_depth; 121, None; 122, block; 122, 123; 123, expression_statement; 123, 124; 124, call; 124, 125; 124, 128; 125, attribute; 125, 126; 125, 127; 126, identifier:level_shape_list; 127, identifier:append; 128, argument_list; 128, 129; 129, call; 129, 130; 129, 131; 130, identifier:depth_profile; 131, argument_list; 131, 132; 131, 133; 132, identifier:item; 133, None; 134, else_clause; 134, 135; 135, block; 135, 136; 136, if_statement; 136, 137; 136, 140; 136, 154; 137, comparison_operator:>=; 137, 138; 137, 139; 138, identifier:max_depth; 139, integer:0; 140, block; 140, 141; 141, expression_statement; 141, 142; 142, call; 142, 143; 142, 146; 143, attribute; 143, 144; 143, 145; 144, identifier:level_shape_list; 145, identifier:append; 146, argument_list; 146, 147; 147, call; 147, 148; 147, 149; 148, identifier:depth_profile; 149, argument_list; 149, 150; 149, 151; 150, identifier:item; 151, binary_operator:-; 151, 152; 151, 153; 152, identifier:max_depth; 153, integer:1; 154, else_clause; 154, 155; 155, block; 155, 156; 156, expression_statement; 156, 157; 157, call; 157, 158; 157, 161; 158, attribute; 158, 159; 158, 160; 159, identifier:level_shape_list; 160, identifier:append; 161, argument_list; 161, 162; 162, call; 162, 163; 162, 164; 163, identifier:str; 164, argument_list; 164, 165; 165, call; 165, 166; 165, 167; 166, identifier:len; 167, argument_list; 167, 168; 168, identifier:item; 169, else_clause; 169, 170; 170, block; 170, 171; 171, expression_statement; 171, 172; 172, call; 172, 173; 172, 176; 173, attribute; 173, 174; 173, 175; 174, identifier:level_shape_list; 175, identifier:append; 176, argument_list; 176, 177; 177, integer:1; 178, if_statement; 178, 179; 178, 180; 178, 181; 179, identifier:compress_homogenous; 180, comment; 181, block; 181, 182; 182, if_statement; 182, 183; 182, 187; 183, call; 183, 184; 183, 185; 184, identifier:allsame; 185, argument_list; 185, 186; 186, identifier:level_shape_list; 187, block; 187, 188; 187, 194; 187, 201; 188, expression_statement; 188, 189; 189, assignment; 189, 190; 189, 191; 190, identifier:dim_; 191, subscript; 191, 192; 191, 193; 192, identifier:level_shape_list; 193, integer:0; 194, expression_statement; 194, 195; 195, assignment; 195, 196; 195, 197; 196, identifier:len_; 197, call; 197, 198; 197, 199; 198, identifier:len; 199, argument_list; 199, 200; 200, identifier:level_shape_list; 201, if_statement; 201, 202; 201, 207; 201, 221; 202, call; 202, 203; 202, 204; 203, identifier:isinstance; 204, argument_list; 204, 205; 204, 206; 205, identifier:dim_; 206, identifier:tuple; 207, block; 207, 208; 208, expression_statement; 208, 209; 209, assignment; 209, 210; 209, 211; 210, identifier:level_shape_list; 211, call; 211, 212; 211, 213; 212, identifier:tuple; 213, argument_list; 213, 214; 214, binary_operator:+; 214, 215; 214, 217; 215, list:[len_]; 215, 216; 216, identifier:len_; 217, call; 217, 218; 217, 219; 218, identifier:list; 219, argument_list; 219, 220; 220, identifier:dim_; 221, else_clause; 221, 222; 222, block; 222, 223; 223, expression_statement; 223, 224; 224, assignment; 224, 225; 224, 226; 225, identifier:level_shape_list; 226, call; 226, 227; 226, 228; 227, identifier:tuple; 228, argument_list; 228, 229; 229, list:[len_, dim_]; 229, 230; 229, 231; 230, identifier:len_; 231, identifier:dim_; 232, if_statement; 232, 233; 232, 234; 233, identifier:compress_consecutive; 234, block; 234, 235; 234, 250; 234, 258; 235, expression_statement; 235, 236; 236, assignment; 236, 237; 236, 238; 237, identifier:hash_list; 238, call; 238, 239; 238, 240; 239, identifier:list; 240, argument_list; 240, 241; 241, call; 241, 242; 241, 243; 242, identifier:map; 243, argument_list; 243, 244; 243, 245; 244, identifier:hash; 245, call; 245, 246; 245, 247; 246, identifier:map; 247, argument_list; 247, 248; 247, 249; 248, identifier:str; 249, identifier:level_shape_list; 250, expression_statement; 250, 251; 251, assignment; 251, 252; 251, 253; 252, identifier:consec_list; 253, call; 253, 254; 253, 255; 254, identifier:group_consecutives; 255, argument_list; 255, 256; 255, 257; 256, identifier:hash_list; 257, integer:0; 258, if_statement; 258, 259; 258, 268; 259, comparison_operator:!=; 259, 260; 259, 264; 260, call; 260, 261; 260, 262; 261, identifier:len; 262, argument_list; 262, 263; 263, identifier:consec_list; 264, call; 264, 265; 264, 266; 265, identifier:len; 266, argument_list; 266, 267; 267, identifier:level_shape_list; 268, block; 268, 269; 268, 280; 268, 289; 268, 293; 268, 297; 268, 349; 268, 367; 268, 368; 268, 369; 268, 370; 268, 371; 268, 375; 269, expression_statement; 269, 270; 270, assignment; 270, 271; 270, 272; 271, identifier:len_list; 272, call; 272, 273; 272, 274; 273, identifier:list; 274, argument_list; 274, 275; 275, call; 275, 276; 275, 277; 276, identifier:map; 277, argument_list; 277, 278; 277, 279; 278, identifier:len; 279, identifier:consec_list; 280, expression_statement; 280, 281; 281, assignment; 281, 282; 281, 283; 282, identifier:cumsum_list; 283, call; 283, 284; 283, 287; 284, attribute; 284, 285; 284, 286; 285, identifier:np; 286, identifier:cumsum; 287, argument_list; 287, 288; 288, identifier:len_list; 289, expression_statement; 289, 290; 290, assignment; 290, 291; 290, 292; 291, identifier:consec_str; 292, string:'['; 293, expression_statement; 293, 294; 294, assignment; 294, 295; 294, 296; 295, identifier:thresh; 296, integer:1; 297, for_statement; 297, 298; 297, 301; 297, 306; 298, pattern_list; 298, 299; 298, 300; 299, identifier:len_; 300, identifier:cumsum; 301, call; 301, 302; 301, 303; 302, identifier:zip; 303, argument_list; 303, 304; 303, 305; 304, identifier:len_list; 305, identifier:cumsum_list; 306, block; 306, 307; 306, 315; 307, expression_statement; 307, 308; 308, assignment; 308, 309; 308, 310; 309, identifier:value; 310, subscript; 310, 311; 310, 312; 311, identifier:level_shape_list; 312, binary_operator:-; 312, 313; 312, 314; 313, identifier:cumsum; 314, integer:1; 315, if_statement; 315, 316; 315, 319; 315, 338; 316, comparison_operator:>; 316, 317; 316, 318; 317, identifier:len_; 318, identifier:thresh; 319, block; 319, 320; 319, 334; 320, expression_statement; 320, 321; 321, augmented_assignment:+=; 321, 322; 321, 323; 322, identifier:consec_str; 323, binary_operator:+; 323, 324; 323, 330; 324, binary_operator:+; 324, 325; 324, 329; 325, call; 325, 326; 325, 327; 326, identifier:str; 327, argument_list; 327, 328; 328, identifier:value; 329, string:'] * '; 330, call; 330, 331; 330, 332; 331, identifier:str; 332, argument_list; 332, 333; 333, identifier:len_; 334, expression_statement; 334, 335; 335, augmented_assignment:+=; 335, 336; 335, 337; 336, identifier:consec_str; 337, string:' + ['; 338, else_clause; 338, 339; 339, block; 339, 340; 340, expression_statement; 340, 341; 341, augmented_assignment:+=; 341, 342; 341, 343; 342, identifier:consec_str; 343, binary_operator:+; 343, 344; 343, 348; 344, call; 344, 345; 344, 346; 345, identifier:str; 346, argument_list; 346, 347; 347, identifier:value; 348, string:', '; 349, if_statement; 349, 350; 349, 356; 350, call; 350, 351; 350, 354; 351, attribute; 351, 352; 351, 353; 352, identifier:consec_str; 353, identifier:endswith; 354, argument_list; 354, 355; 355, string:', '; 356, block; 356, 357; 356, 366; 357, expression_statement; 357, 358; 358, assignment; 358, 359; 358, 360; 359, identifier:consec_str; 360, subscript; 360, 361; 360, 362; 361, identifier:consec_str; 362, slice; 362, 363; 362, 364; 363, colon; 364, unary_operator:-; 364, 365; 365, integer:2; 366, comment; 367, comment; 368, comment; 369, comment; 370, comment; 371, expression_statement; 371, 372; 372, augmented_assignment:+=; 372, 373; 372, 374; 373, identifier:consec_str; 374, string:']'; 375, expression_statement; 375, 376; 376, assignment; 376, 377; 376, 378; 377, identifier:level_shape_list; 378, identifier:consec_str; 379, return_statement; 379, 380; 380, identifier:level_shape_list
def depth_profile(list_, max_depth=None, compress_homogenous=True, compress_consecutive=False, new_depth=False): r""" Returns a nested list corresponding the shape of the nested structures lists represent depth, tuples represent shape. The values of the items do not matter. only the lengths. Args: list_ (list): max_depth (None): compress_homogenous (bool): compress_consecutive (bool): experimental CommandLine: python -m utool.util_list --test-depth_profile Setup: >>> from utool.util_list import * # NOQA Example0: >>> # ENABLE_DOCTEST >>> list_ = [[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]] >>> result = depth_profile(list_) >>> print(result) (2, 3, 4) Example1: >>> # ENABLE_DOCTEST >>> list_ = [[[[[1]]], [3, 4, 33]], [[1], [2, 3], [4, [5, 5]]], [1, 3]] >>> result = depth_profile(list_) >>> print(result) [[(1, 1, 1), 3], [1, 2, [1, 2]], 2] Example2: >>> # ENABLE_DOCTEST >>> list_ = [[[[[1]]], [3, 4, 33]], [[1], [2, 3], [4, [5, 5]]], [1, 3]] >>> result = depth_profile(list_, max_depth=1) >>> print(result) [[(1, '1'), 3], [1, 2, [1, '2']], 2] Example3: >>> # ENABLE_DOCTEST >>> list_ = [[[1, 2], [1, 2, 3]], None] >>> result = depth_profile(list_, compress_homogenous=True) >>> print(result) [[2, 3], 1] Example4: >>> # ENABLE_DOCTEST >>> list_ = [[3, 2], [3, 2], [3, 2], [3, 2], [3, 2], [3, 2], [9, 5, 3], [2, 2]] >>> result = depth_profile(list_, compress_homogenous=True, compress_consecutive=True) >>> print(result) [2] * 6 + [3, 2] Example5: >>> # ENABLE_DOCTEST >>> list_ = [[[3, 9], 2], [[3, 9], 2], [[3, 9], 2], [[3, 9], 2]] #, [3, 2], [3, 2]] >>> result = depth_profile(list_, compress_homogenous=True, compress_consecutive=True) >>> print(result) (4, [2, 1]) Example6: >>> # ENABLE_DOCTEST >>> list_ = [[[[1, 2]], [1, 2]], [[[1, 2]], [1, 2]], [[[0, 2]], [1]]] >>> result1 = depth_profile(list_, compress_homogenous=True, compress_consecutive=False) >>> result2 = depth_profile(list_, compress_homogenous=True, compress_consecutive=True) >>> result = str(result1) + '\n' + str(result2) >>> print(result) [[(1, 2), 2], [(1, 2), 2], [(1, 2), 1]] [[(1, 2), 2]] * 2 + [[(1, 2), 1]] Example7: >>> # ENABLE_DOCTEST >>> list_ = [[{'a': [1, 2], 'b': [3, 4, 5]}, [1, 2, 3]], None] >>> result = depth_profile(list_, compress_homogenous=True) >>> print(result) Example8: >>> # ENABLE_DOCTEST >>> list_ = [[[1]], [[[1, 1], [1, 1]]], [[[[1, 3], 1], [[1, 3, 3], 1, 1]]]] >>> result = depth_profile(list_, compress_homogenous=True) >>> print(result) Example9: >>> # ENABLE_DOCTEST >>> list_ = [] >>> result = depth_profile(list_) >>> print(result) # THIS IS AN ERROR??? SHOULD BE #[1, 1], [1, 2, 2], (1, ([1, 2]), ( Example10: >>> # ENABLE_DOCTEST >>> fm1 = [[0, 0], [0, 0]] >>> fm2 = [[0, 0], [0, 0], [0, 0]] >>> fm3 = [[0, 0], [0, 0], [0, 0], [0, 0]] >>> list_ = [0, 0, 0] >>> list_ = [fm1, fm2, fm3] >>> max_depth = 0 >>> new_depth = True >>> result = depth_profile(list_, max_depth=max_depth, new_depth=new_depth) >>> print(result) """ if isinstance(list_, dict): list_ = list(list_.values()) # handle dict level_shape_list = [] # For a pure bottom level list return the length if not any(map(util_type.is_listlike, list_)): return len(list_) if False and new_depth: pass # max_depth_ = None if max_depth is None else max_depth - 1 # if max_depth_ is None or max_depth_ > 0: # pass # else: # for item in list_: # if isinstance(item, dict): # item = list(item.values()) # handle dict # if util_type.is_listlike(item): # if max_depth is None: # level_shape_list.append(depth_profile(item, None)) # else: # if max_depth >= 0: # level_shape_list.append(depth_profile(item, max_depth - 1)) # else: # level_shape_list.append(str(len(item))) # else: # level_shape_list.append(1) else: for item in list_: if isinstance(item, dict): item = list(item.values()) # handle dict if util_type.is_listlike(item): if max_depth is None: level_shape_list.append(depth_profile(item, None)) else: if max_depth >= 0: level_shape_list.append(depth_profile(item, max_depth - 1)) else: level_shape_list.append(str(len(item))) else: level_shape_list.append(1) if compress_homogenous: # removes redudant information by returning a shape duple if allsame(level_shape_list): dim_ = level_shape_list[0] len_ = len(level_shape_list) if isinstance(dim_, tuple): level_shape_list = tuple([len_] + list(dim_)) else: level_shape_list = tuple([len_, dim_]) if compress_consecutive: hash_list = list(map(hash, map(str, level_shape_list))) consec_list = group_consecutives(hash_list, 0) if len(consec_list) != len(level_shape_list): len_list = list(map(len, consec_list)) cumsum_list = np.cumsum(len_list) consec_str = '[' thresh = 1 for len_, cumsum in zip(len_list, cumsum_list): value = level_shape_list[cumsum - 1] if len_ > thresh: consec_str += str(value) + '] * ' + str(len_) consec_str += ' + [' else: consec_str += str(value) + ', ' if consec_str.endswith(', '): consec_str = consec_str[:-2] #consec_str += ']' #consec_str = consec_str.rstrip(', ').rstrip(']') #consec_str = consec_str.rstrip(', ') #if consec_str.endswith(']'): # consec_str = consec_str[:-1] consec_str += ']' level_shape_list = consec_str return level_shape_list
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 9; 2, function_name:list_alignment; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:list1; 5, identifier:list2; 6, default_parameter; 6, 7; 6, 8; 7, identifier:missing; 8, False; 9, block; 9, 10; 9, 12; 9, 17; 9, 24; 9, 50; 10, expression_statement; 10, 11; 11, comment; 12, import_statement; 12, 13; 13, aliased_import; 13, 14; 13, 16; 14, dotted_name; 14, 15; 15, identifier:utool; 16, identifier:ut; 17, expression_statement; 17, 18; 18, assignment; 18, 19; 18, 20; 19, identifier:item1_to_idx; 20, call; 20, 21; 20, 22; 21, identifier:make_index_lookup; 22, argument_list; 22, 23; 23, identifier:list1; 24, if_statement; 24, 25; 24, 26; 24, 38; 25, identifier:missing; 26, block; 26, 27; 27, expression_statement; 27, 28; 28, assignment; 28, 29; 28, 30; 29, identifier:sortx; 30, call; 30, 31; 30, 34; 31, attribute; 31, 32; 31, 33; 32, identifier:ut; 33, identifier:dict_take; 34, argument_list; 34, 35; 34, 36; 34, 37; 35, identifier:item1_to_idx; 36, identifier:list2; 37, None; 38, else_clause; 38, 39; 39, block; 39, 40; 40, expression_statement; 40, 41; 41, assignment; 41, 42; 41, 43; 42, identifier:sortx; 43, call; 43, 44; 43, 47; 44, attribute; 44, 45; 44, 46; 45, identifier:ut; 46, identifier:take; 47, argument_list; 47, 48; 47, 49; 48, identifier:item1_to_idx; 49, identifier:list2; 50, return_statement; 50, 51; 51, identifier:sortx
def list_alignment(list1, list2, missing=False): """ Assumes list items are unique Args: list1 (list): a list of unique items to be aligned list2 (list): a list of unique items in a desired ordering missing (bool): True if list2 can contain items not in list1 Returns: list: sorting that will map list1 onto list2 CommandLine: python -m utool.util_list list_alignment Example: >>> # ENABLE_DOCTEST >>> from utool.util_list import * # NOQA >>> import utool as ut >>> list1 = ['b', 'c', 'a'] >>> list2 = ['a', 'b', 'c'] >>> sortx = list_alignment(list1, list2) >>> list1_aligned = take(list1, sortx) >>> assert list1_aligned == list2 Example1: >>> # ENABLE_DOCTEST >>> from utool.util_list import * # NOQA >>> import utool as ut >>> list1 = ['b', 'c', 'a'] >>> list2 = ['a', 'a2', 'b', 'c', 'd'] >>> sortx = ut.list_alignment(list1, list2, missing=True) >>> print('sortx = %r' % (sortx,)) >>> list1_aligned = ut.none_take(list1, sortx) >>> result = ('list1_aligned = %s' % (ut.repr2(list1_aligned),)) >>> print(result) list1_aligned = ['a', None, 'b', 'c', None] """ import utool as ut item1_to_idx = make_index_lookup(list1) if missing: sortx = ut.dict_take(item1_to_idx, list2, None) else: sortx = ut.take(item1_to_idx, list2) return sortx
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:_update_hasher; 3, parameters; 3, 4; 3, 5; 4, identifier:hasher; 5, identifier:data; 6, block; 6, 7; 6, 9; 6, 56; 7, expression_statement; 7, 8; 8, comment; 9, if_statement; 9, 10; 9, 18; 9, 23; 9, 50; 10, call; 10, 11; 10, 12; 11, identifier:isinstance; 12, argument_list; 12, 13; 12, 14; 13, identifier:data; 14, tuple; 14, 15; 14, 16; 14, 17; 15, identifier:tuple; 16, identifier:list; 17, identifier:zip; 18, block; 18, 19; 19, expression_statement; 19, 20; 20, assignment; 20, 21; 20, 22; 21, identifier:needs_iteration; 22, True; 23, elif_clause; 23, 24; 23, 44; 23, 45; 24, parenthesized_expression; 24, 25; 25, boolean_operator:and; 25, 26; 25, 37; 26, boolean_operator:and; 26, 27; 26, 30; 27, attribute; 27, 28; 27, 29; 28, identifier:util_type; 29, identifier:HAVE_NUMPY; 30, call; 30, 31; 30, 32; 31, identifier:isinstance; 32, argument_list; 32, 33; 32, 34; 33, identifier:data; 34, attribute; 34, 35; 34, 36; 35, identifier:np; 36, identifier:ndarray; 37, comparison_operator:==; 37, 38; 37, 43; 38, attribute; 38, 39; 38, 42; 39, attribute; 39, 40; 39, 41; 40, identifier:data; 41, identifier:dtype; 42, identifier:kind; 43, string:'O'; 44, comment; 45, block; 45, 46; 46, expression_statement; 46, 47; 47, assignment; 47, 48; 47, 49; 48, identifier:needs_iteration; 49, True; 50, else_clause; 50, 51; 51, block; 51, 52; 52, expression_statement; 52, 53; 53, assignment; 53, 54; 53, 55; 54, identifier:needs_iteration; 55, False; 56, if_statement; 56, 57; 56, 58; 56, 59; 56, 146; 57, identifier:needs_iteration; 58, comment; 59, block; 59, 60; 59, 64; 59, 68; 59, 69; 59, 70; 59, 71; 59, 72; 59, 79; 59, 86; 60, expression_statement; 60, 61; 61, assignment; 61, 62; 61, 63; 62, identifier:SEP; 63, string:b'SEP'; 64, expression_statement; 64, 65; 65, assignment; 65, 66; 65, 67; 66, identifier:iter_prefix; 67, string:b'ITER'; 68, comment; 69, comment; 70, comment; 71, comment; 72, expression_statement; 72, 73; 73, assignment; 73, 74; 73, 75; 74, identifier:iter_; 75, call; 75, 76; 75, 77; 76, identifier:iter; 77, argument_list; 77, 78; 78, identifier:data; 79, expression_statement; 79, 80; 80, call; 80, 81; 80, 84; 81, attribute; 81, 82; 81, 83; 82, identifier:hasher; 83, identifier:update; 84, argument_list; 84, 85; 85, identifier:iter_prefix; 86, try_statement; 86, 87; 86, 117; 87, block; 87, 88; 88, for_statement; 88, 89; 88, 90; 88, 91; 89, identifier:item; 90, identifier:iter_; 91, block; 91, 92; 91, 101; 91, 109; 91, 110; 92, expression_statement; 92, 93; 93, assignment; 93, 94; 93, 97; 94, pattern_list; 94, 95; 94, 96; 95, identifier:prefix; 96, identifier:hashable; 97, call; 97, 98; 97, 99; 98, identifier:_covert_to_hashable; 99, argument_list; 99, 100; 100, identifier:data; 101, expression_statement; 101, 102; 102, assignment; 102, 103; 102, 104; 103, identifier:binary_data; 104, binary_operator:+; 104, 105; 104, 108; 105, binary_operator:+; 105, 106; 105, 107; 106, identifier:SEP; 107, identifier:prefix; 108, identifier:hashable; 109, comment; 110, expression_statement; 110, 111; 111, call; 111, 112; 111, 115; 112, attribute; 112, 113; 112, 114; 113, identifier:hasher; 114, identifier:update; 115, argument_list; 115, 116; 116, identifier:binary_data; 117, except_clause; 117, 118; 117, 119; 117, 120; 117, 121; 118, identifier:TypeError; 119, comment; 120, comment; 121, block; 121, 122; 121, 128; 122, expression_statement; 122, 123; 123, call; 123, 124; 123, 125; 124, identifier:_update_hasher; 125, argument_list; 125, 126; 125, 127; 126, identifier:hasher; 127, identifier:item; 128, for_statement; 128, 129; 128, 130; 128, 131; 128, 132; 129, identifier:item; 130, identifier:iter_; 131, comment; 132, block; 132, 133; 132, 140; 133, expression_statement; 133, 134; 134, call; 134, 135; 134, 138; 135, attribute; 135, 136; 135, 137; 136, identifier:hasher; 137, identifier:update; 138, argument_list; 138, 139; 139, identifier:SEP; 140, expression_statement; 140, 141; 141, call; 141, 142; 141, 143; 142, identifier:_update_hasher; 143, argument_list; 143, 144; 143, 145; 144, identifier:hasher; 145, identifier:item; 146, else_clause; 146, 147; 147, block; 147, 148; 147, 157; 147, 163; 147, 164; 148, expression_statement; 148, 149; 149, assignment; 149, 150; 149, 153; 150, pattern_list; 150, 151; 150, 152; 151, identifier:prefix; 152, identifier:hashable; 153, call; 153, 154; 153, 155; 154, identifier:_covert_to_hashable; 155, argument_list; 155, 156; 156, identifier:data; 157, expression_statement; 157, 158; 158, assignment; 158, 159; 158, 160; 159, identifier:binary_data; 160, binary_operator:+; 160, 161; 160, 162; 161, identifier:prefix; 162, identifier:hashable; 163, comment; 164, expression_statement; 164, 165; 165, call; 165, 166; 165, 169; 166, attribute; 166, 167; 166, 168; 167, identifier:hasher; 168, identifier:update; 169, argument_list; 169, 170; 170, identifier:binary_data
def _update_hasher(hasher, data): """ This is the clear winner over the generate version. Used by hash_data Ignore: import utool rng = np.random.RandomState(0) # str1 = rng.rand(0).dumps() str1 = b'SEP' str2 = rng.rand(10000).dumps() for timer in utool.Timerit(100, label='twocall'): hasher = hashlib.sha256() with timer: hasher.update(str1) hasher.update(str2) a = hasher.hexdigest() for timer in utool.Timerit(100, label='concat'): hasher = hashlib.sha256() with timer: hasher.update(str1 + str2) b = hasher.hexdigest() assert a == b # CONCLUSION: Faster to concat in case of prefixes and seps nested_data = {'1': [rng.rand(100), '2', '3'], '2': ['1', '2', '3', '4', '5'], '3': [('1', '2'), ('3', '4'), ('5', '6')]} data = list(nested_data.values()) for timer in utool.Timerit(1000, label='cat-generate'): hasher = hashlib.sha256() with timer: hasher.update(b''.join(_bytes_generator(data))) for timer in utool.Timerit(1000, label='inc-generate'): hasher = hashlib.sha256() with timer: for b in _bytes_generator(data): hasher.update(b) for timer in utool.Timerit(1000, label='inc-generate'): hasher = hashlib.sha256() with timer: for b in _bytes_generator(data): hasher.update(b) for timer in utool.Timerit(1000, label='chunk-inc-generate'): hasher = hashlib.sha256() import ubelt as ub with timer: for chunk in ub.chunks(_bytes_generator(data), 5): hasher.update(b''.join(chunk)) for timer in utool.Timerit(1000, label='inc-update'): hasher = hashlib.sha256() with timer: _update_hasher(hasher, data) data = ut.lorium_ipsum() hash_data(data) ut.hashstr27(data) %timeit hash_data(data) %timeit ut.hashstr27(repr(data)) for timer in utool.Timerit(100, label='twocall'): hasher = hashlib.sha256() with timer: hash_data(data) hasher = hashlib.sha256() hasher.update(memoryview(np.array([1]))) print(hasher.hexdigest()) hasher = hashlib.sha256() hasher.update(np.array(['1'], dtype=object)) print(hasher.hexdigest()) """ if isinstance(data, (tuple, list, zip)): needs_iteration = True elif (util_type.HAVE_NUMPY and isinstance(data, np.ndarray) and data.dtype.kind == 'O'): # ndarrays of objects cannot be hashed directly. needs_iteration = True else: needs_iteration = False if needs_iteration: # try to nest quickly without recursive calls SEP = b'SEP' iter_prefix = b'ITER' # if isinstance(data, tuple): # iter_prefix = b'TUP' # else: # iter_prefix = b'LIST' iter_ = iter(data) hasher.update(iter_prefix) try: for item in iter_: prefix, hashable = _covert_to_hashable(data) binary_data = SEP + prefix + hashable # b''.join([SEP, prefix, hashable]) hasher.update(binary_data) except TypeError: # need to use recursive calls # Update based on current item _update_hasher(hasher, item) for item in iter_: # Ensure the items have a spacer between them hasher.update(SEP) _update_hasher(hasher, item) else: prefix, hashable = _covert_to_hashable(data) binary_data = prefix + hashable # b''.join([prefix, hashable]) hasher.update(binary_data)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 11; 2, function_name:hash_data; 3, parameters; 3, 4; 3, 5; 3, 8; 4, identifier:data; 5, default_parameter; 5, 6; 5, 7; 6, identifier:hashlen; 7, None; 8, default_parameter; 8, 9; 8, 10; 9, identifier:alphabet; 10, None; 11, block; 11, 12; 11, 14; 11, 23; 11, 32; 12, expression_statement; 12, 13; 13, comment; 14, if_statement; 14, 15; 14, 18; 15, comparison_operator:is; 15, 16; 15, 17; 16, identifier:alphabet; 17, None; 18, block; 18, 19; 19, expression_statement; 19, 20; 20, assignment; 20, 21; 20, 22; 21, identifier:alphabet; 22, identifier:ALPHABET_27; 23, if_statement; 23, 24; 23, 27; 24, comparison_operator:is; 24, 25; 24, 26; 25, identifier:hashlen; 26, None; 27, block; 27, 28; 28, expression_statement; 28, 29; 29, assignment; 29, 30; 29, 31; 30, identifier:hashlen; 31, identifier:HASH_LEN2; 32, if_statement; 32, 33; 32, 45; 32, 46; 32, 56; 33, boolean_operator:and; 33, 34; 33, 39; 34, call; 34, 35; 34, 36; 35, identifier:isinstance; 36, argument_list; 36, 37; 36, 38; 37, identifier:data; 38, identifier:stringlike; 39, comparison_operator:==; 39, 40; 39, 44; 40, call; 40, 41; 40, 42; 41, identifier:len; 42, argument_list; 42, 43; 43, identifier:data; 44, integer:0; 45, comment; 46, block; 46, 47; 47, expression_statement; 47, 48; 48, assignment; 48, 49; 48, 50; 49, identifier:text; 50, parenthesized_expression; 50, 51; 51, binary_operator:*; 51, 52; 51, 55; 52, subscript; 52, 53; 52, 54; 53, identifier:alphabet; 54, integer:0; 55, identifier:hashlen; 56, else_clause; 56, 57; 57, block; 57, 58; 57, 66; 57, 72; 57, 73; 57, 81; 57, 82; 57, 96; 57, 97; 57, 105; 58, expression_statement; 58, 59; 59, assignment; 59, 60; 59, 61; 60, identifier:hasher; 61, call; 61, 62; 61, 65; 62, attribute; 62, 63; 62, 64; 63, identifier:hashlib; 64, identifier:sha512; 65, argument_list; 66, expression_statement; 66, 67; 67, call; 67, 68; 67, 69; 68, identifier:_update_hasher; 69, argument_list; 69, 70; 69, 71; 70, identifier:hasher; 71, identifier:data; 72, comment; 73, expression_statement; 73, 74; 74, assignment; 74, 75; 74, 76; 75, identifier:text; 76, call; 76, 77; 76, 80; 77, attribute; 77, 78; 77, 79; 78, identifier:hasher; 79, identifier:hexdigest; 80, argument_list; 81, comment; 82, expression_statement; 82, 83; 83, assignment; 83, 84; 83, 85; 84, identifier:hashstr2; 85, call; 85, 86; 85, 87; 86, identifier:convert_hexstr_to_bigbase; 87, argument_list; 87, 88; 87, 89; 87, 90; 88, identifier:text; 89, identifier:alphabet; 90, keyword_argument; 90, 91; 90, 92; 91, identifier:bigbase; 92, call; 92, 93; 92, 94; 93, identifier:len; 94, argument_list; 94, 95; 95, identifier:alphabet; 96, comment; 97, expression_statement; 97, 98; 98, assignment; 98, 99; 98, 100; 99, identifier:text; 100, subscript; 100, 101; 100, 102; 101, identifier:hashstr2; 102, slice; 102, 103; 102, 104; 103, colon; 104, identifier:hashlen; 105, return_statement; 105, 106; 106, identifier:text
def hash_data(data, hashlen=None, alphabet=None): r""" Get a unique hash depending on the state of the data. Args: data (object): any sort of loosely organized data hashlen (None): (default = None) alphabet (None): (default = None) Returns: str: text - hash string CommandLine: python -m utool.util_hash hash_data Example: >>> # ENABLE_DOCTEST >>> from utool.util_hash import * # NOQA >>> import utool as ut >>> counter = [0] >>> failed = [] >>> def check_hash(input_, want=None): >>> count = counter[0] = counter[0] + 1 >>> got = ut.hash_data(input_) >>> print('({}) {}'.format(count, got)) >>> if want is not None and not got.startswith(want): >>> failed.append((got, input_, count, want)) >>> check_hash('1', 'wuvrng') >>> check_hash(['1'], 'dekbfpby') >>> check_hash(tuple(['1']), 'dekbfpby') >>> check_hash(b'12', 'marreflbv') >>> check_hash([b'1', b'2'], 'nwfs') >>> check_hash(['1', '2', '3'], 'arfrp') >>> check_hash(['1', np.array([1,2,3]), '3'], 'uyqwcq') >>> check_hash('123', 'ehkgxk') >>> check_hash(zip([1, 2, 3], [4, 5, 6]), 'mjcpwa') >>> import numpy as np >>> rng = np.random.RandomState(0) >>> check_hash(rng.rand(100000), 'bdwosuey') >>> for got, input_, count, want in failed: >>> print('failed {} on {}'.format(count, input_)) >>> print('got={}, want={}'.format(got, want)) >>> assert not failed """ if alphabet is None: alphabet = ALPHABET_27 if hashlen is None: hashlen = HASH_LEN2 if isinstance(data, stringlike) and len(data) == 0: # Make a special hash for empty data text = (alphabet[0] * hashlen) else: hasher = hashlib.sha512() _update_hasher(hasher, data) # Get a 128 character hex string text = hasher.hexdigest() # Shorten length of string (by increasing base) hashstr2 = convert_hexstr_to_bigbase(text, alphabet, bigbase=len(alphabet)) # Truncate text = hashstr2[:hashlen] return text
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 15; 2, function_name:quick_search; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 3, 12; 4, identifier:self; 5, identifier:name; 6, default_parameter; 6, 7; 6, 8; 7, identifier:platform; 8, None; 9, default_parameter; 9, 10; 9, 11; 10, identifier:sort_by; 11, None; 12, default_parameter; 12, 13; 12, 14; 13, identifier:desc; 14, True; 15, block; 15, 16; 15, 18; 15, 44; 15, 51; 15, 92; 15, 101; 16, expression_statement; 16, 17; 17, comment; 18, if_statement; 18, 19; 18, 22; 18, 32; 19, comparison_operator:is; 19, 20; 19, 21; 20, identifier:platform; 21, None; 22, block; 22, 23; 23, expression_statement; 23, 24; 24, assignment; 24, 25; 24, 26; 25, identifier:query_filter; 26, call; 26, 27; 26, 30; 27, attribute; 27, 28; 27, 29; 28, string:"name:{0}"; 29, identifier:format; 30, argument_list; 30, 31; 31, identifier:name; 32, else_clause; 32, 33; 33, block; 33, 34; 34, expression_statement; 34, 35; 35, assignment; 35, 36; 35, 37; 36, identifier:query_filter; 37, call; 37, 38; 37, 41; 38, attribute; 38, 39; 38, 40; 39, string:"name:{0},platforms:{1}"; 40, identifier:format; 41, argument_list; 41, 42; 41, 43; 42, identifier:name; 43, identifier:platform; 44, expression_statement; 44, 45; 45, assignment; 45, 46; 45, 47; 46, identifier:search_params; 47, dictionary; 47, 48; 48, pair; 48, 49; 48, 50; 49, string:"filter"; 50, identifier:query_filter; 51, if_statement; 51, 52; 51, 55; 52, comparison_operator:is; 52, 53; 52, 54; 53, identifier:sort_by; 54, None; 55, block; 55, 56; 55, 63; 55, 80; 56, expression_statement; 56, 57; 57, call; 57, 58; 57, 61; 58, attribute; 58, 59; 58, 60; 59, identifier:self; 60, identifier:_validate_sort_field; 61, argument_list; 61, 62; 62, identifier:sort_by; 63, if_statement; 63, 64; 63, 65; 63, 72; 64, identifier:desc; 65, block; 65, 66; 66, expression_statement; 66, 67; 67, assignment; 67, 68; 67, 69; 68, identifier:direction; 69, attribute; 69, 70; 69, 71; 70, identifier:self; 71, identifier:SORT_ORDER_DESCENDING; 72, else_clause; 72, 73; 73, block; 73, 74; 74, expression_statement; 74, 75; 75, assignment; 75, 76; 75, 77; 76, identifier:direction; 77, attribute; 77, 78; 77, 79; 78, identifier:self; 79, identifier:SORT_ORDER_ASCENDING; 80, expression_statement; 80, 81; 81, assignment; 81, 82; 81, 85; 82, subscript; 82, 83; 82, 84; 83, identifier:search_params; 84, string:"sort"; 85, call; 85, 86; 85, 89; 86, attribute; 86, 87; 86, 88; 87, string:"{0}:{1}"; 88, identifier:format; 89, argument_list; 89, 90; 89, 91; 90, identifier:sort_by; 91, identifier:direction; 92, expression_statement; 92, 93; 93, assignment; 93, 94; 93, 95; 94, identifier:response; 95, call; 95, 96; 95, 99; 96, attribute; 96, 97; 96, 98; 97, identifier:self; 98, identifier:_query; 99, argument_list; 99, 100; 100, identifier:search_params; 101, return_statement; 101, 102; 102, identifier:response
def quick_search(self, name, platform=None, sort_by=None, desc=True): """ Quick search method that allows you to search for a game using only the title and the platform :param name: string :param platform: int :param sort_by: string :param desc: bool :return: pybomb.clients.Response """ if platform is None: query_filter = "name:{0}".format(name) else: query_filter = "name:{0},platforms:{1}".format(name, platform) search_params = {"filter": query_filter} if sort_by is not None: self._validate_sort_field(sort_by) if desc: direction = self.SORT_ORDER_DESCENDING else: direction = self.SORT_ORDER_ASCENDING search_params["sort"] = "{0}:{1}".format(sort_by, direction) response = self._query(search_params) return response
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:smart_cast; 3, parameters; 3, 4; 3, 5; 4, identifier:var; 5, identifier:type_; 6, block; 6, 7; 6, 9; 6, 10; 6, 11; 6, 12; 6, 13; 6, 14; 6, 15; 6, 16; 6, 27; 6, 28; 6, 46; 6, 164; 7, expression_statement; 7, 8; 8, comment; 9, comment; 10, comment; 11, comment; 12, comment; 13, comment; 14, comment; 15, comment; 16, if_statement; 16, 17; 16, 24; 17, boolean_operator:or; 17, 18; 17, 21; 18, comparison_operator:is; 18, 19; 18, 20; 19, identifier:type_; 20, None; 21, comparison_operator:is; 21, 22; 21, 23; 22, identifier:var; 23, None; 24, block; 24, 25; 25, return_statement; 25, 26; 26, identifier:var; 27, comment; 28, try_statement; 28, 29; 28, 42; 29, block; 29, 30; 30, if_statement; 30, 31; 30, 39; 31, call; 31, 32; 31, 33; 32, identifier:issubclass; 33, argument_list; 33, 34; 33, 35; 34, identifier:type_; 35, call; 35, 36; 35, 37; 36, identifier:type; 37, argument_list; 37, 38; 38, None; 39, block; 39, 40; 40, return_statement; 40, 41; 41, identifier:var; 42, except_clause; 42, 43; 42, 44; 43, identifier:TypeError; 44, block; 44, 45; 45, pass_statement; 46, if_statement; 46, 47; 46, 51; 47, call; 47, 48; 47, 49; 48, identifier:is_str; 49, argument_list; 49, 50; 50, identifier:var; 51, block; 51, 52; 52, if_statement; 52, 53; 52, 56; 52, 62; 52, 97; 52, 121; 53, comparison_operator:in; 53, 54; 53, 55; 54, identifier:type_; 55, identifier:VALID_BOOL_TYPES; 56, block; 56, 57; 57, return_statement; 57, 58; 58, call; 58, 59; 58, 60; 59, identifier:bool_from_str; 60, argument_list; 60, 61; 61, identifier:var; 62, elif_clause; 62, 63; 62, 66; 63, comparison_operator:is; 63, 64; 63, 65; 64, identifier:type_; 65, identifier:slice; 66, block; 66, 67; 66, 91; 67, expression_statement; 67, 68; 68, assignment; 68, 69; 68, 70; 69, identifier:args; 70, list_comprehension; 70, 71; 70, 83; 71, conditional_expression:if; 71, 72; 71, 73; 71, 79; 72, None; 73, comparison_operator:==; 73, 74; 73, 78; 74, call; 74, 75; 74, 76; 75, identifier:len; 76, argument_list; 76, 77; 77, identifier:arg; 78, integer:0; 79, call; 79, 80; 79, 81; 80, identifier:int; 81, argument_list; 81, 82; 82, identifier:arg; 83, for_in_clause; 83, 84; 83, 85; 84, identifier:arg; 85, call; 85, 86; 85, 89; 86, attribute; 86, 87; 86, 88; 87, identifier:var; 88, identifier:split; 89, argument_list; 89, 90; 90, string:':'; 91, return_statement; 91, 92; 92, call; 92, 93; 92, 94; 93, identifier:slice; 94, argument_list; 94, 95; 95, list_splat; 95, 96; 96, identifier:args; 97, elif_clause; 97, 98; 97, 101; 97, 102; 98, comparison_operator:is; 98, 99; 98, 100; 99, identifier:type_; 100, identifier:list; 101, comment; 102, block; 102, 103; 102, 112; 103, expression_statement; 103, 104; 104, assignment; 104, 105; 104, 106; 105, identifier:subvar_list; 106, call; 106, 107; 106, 110; 107, attribute; 107, 108; 107, 109; 108, identifier:var; 109, identifier:split; 110, argument_list; 110, 111; 111, string:','; 112, return_statement; 112, 113; 113, list_comprehension; 113, 114; 113, 118; 114, call; 114, 115; 114, 116; 115, identifier:smart_cast2; 116, argument_list; 116, 117; 117, identifier:subvar; 118, for_in_clause; 118, 119; 118, 120; 119, identifier:subvar; 120, identifier:subvar_list; 121, elif_clause; 121, 122; 121, 129; 122, call; 122, 123; 122, 124; 123, identifier:isinstance; 124, argument_list; 124, 125; 124, 126; 125, identifier:type_; 126, attribute; 126, 127; 126, 128; 127, identifier:six; 128, identifier:string_types; 129, block; 129, 130; 129, 140; 130, if_statement; 130, 131; 130, 134; 131, comparison_operator:==; 131, 132; 131, 133; 132, identifier:type_; 133, string:'fuzzy_subset'; 134, block; 134, 135; 135, return_statement; 135, 136; 136, call; 136, 137; 136, 138; 137, identifier:fuzzy_subset; 138, argument_list; 138, 139; 139, identifier:var; 140, if_statement; 140, 141; 140, 144; 140, 152; 140, 153; 140, 154; 141, comparison_operator:==; 141, 142; 141, 143; 142, identifier:type_; 143, string:'eval'; 144, block; 144, 145; 145, return_statement; 145, 146; 146, call; 146, 147; 146, 148; 147, identifier:eval; 148, argument_list; 148, 149; 148, 150; 148, 151; 149, identifier:var; 150, dictionary; 151, dictionary; 152, comment; 153, comment; 154, else_clause; 154, 155; 155, block; 155, 156; 156, raise_statement; 156, 157; 157, call; 157, 158; 157, 159; 158, identifier:NotImplementedError; 159, argument_list; 159, 160; 160, binary_operator:%; 160, 161; 160, 162; 161, string:'Uknown smart type_=%r'; 162, tuple; 162, 163; 163, identifier:type_; 164, return_statement; 164, 165; 165, call; 165, 166; 165, 167; 166, identifier:type_; 167, argument_list; 167, 168; 168, identifier:var
def smart_cast(var, type_): """ casts var to type, and tries to be clever when var is a string Args: var (object): variable to cast type_ (type or str): type to attempt to cast to Returns: object: CommandLine: python -m utool.util_type --exec-smart_cast Example: >>> # ENABLE_DOCTEST >>> from utool.util_type import * # NOQA >>> var = '1' >>> type_ = 'fuzzy_subset' >>> cast_var = smart_cast(var, type_) >>> result = repr(cast_var) >>> print(result) [1] Example1: >>> # ENABLE_DOCTEST >>> from utool.util_type import * # NOQA >>> import utool as ut >>> cast_var = smart_cast('1', None) >>> result = ut.repr2(cast_var) >>> print(result) '1' Example2: >>> # ENABLE_DOCTEST >>> from utool.util_type import * # NOQA >>> cast_var = smart_cast('(1,3)', 'eval') >>> result = repr(cast_var) >>> print(result) (1, 3) Example3: >>> # ENABLE_DOCTEST >>> from utool.util_type import * # NOQA >>> cast_var = smart_cast('(1,3)', eval) >>> result = repr(cast_var) >>> print(result) (1, 3) Example4: >>> # ENABLE_DOCTEST >>> from utool.util_type import * # NOQA >>> cast_var = smart_cast('1::3', slice) >>> result = repr(cast_var) >>> print(result) slice(1, None, 3) """ #if isinstance(type_, tuple): # for trytype in type_: # try: # return trytype(var) # except Exception: # pass # raise TypeError('Cant figure out type=%r' % (type_,)) if type_ is None or var is None: return var #if not isinstance(type_, six.string_types): try: if issubclass(type_, type(None)): return var except TypeError: pass if is_str(var): if type_ in VALID_BOOL_TYPES: return bool_from_str(var) elif type_ is slice: args = [None if len(arg) == 0 else int(arg) for arg in var.split(':')] return slice(*args) elif type_ is list: # need more intelligent parsing here subvar_list = var.split(',') return [smart_cast2(subvar) for subvar in subvar_list] elif isinstance(type_, six.string_types): if type_ == 'fuzzy_subset': return fuzzy_subset(var) if type_ == 'eval': return eval(var, {}, {}) #elif type_ == 'fuzzy_int': # return fuzzy_subset(var) else: raise NotImplementedError('Uknown smart type_=%r' % (type_,)) return type_(var)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 18; 2, function_name:dump_autogen_code; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 3, 12; 3, 15; 4, identifier:fpath; 5, identifier:autogen_text; 6, default_parameter; 6, 7; 6, 8; 7, identifier:codetype; 8, string:'python'; 9, default_parameter; 9, 10; 9, 11; 10, identifier:fullprint; 11, None; 12, default_parameter; 12, 13; 12, 14; 13, identifier:show_diff; 14, None; 15, default_parameter; 15, 16; 15, 17; 16, identifier:dowrite; 17, None; 18, block; 18, 19; 18, 21; 18, 26; 18, 42; 18, 56; 18, 71; 18, 79; 18, 94; 18, 103; 18, 117; 18, 125; 18, 167; 19, expression_statement; 19, 20; 20, comment; 21, import_statement; 21, 22; 22, aliased_import; 22, 23; 22, 25; 23, dotted_name; 23, 24; 24, identifier:utool; 25, identifier:ut; 26, if_statement; 26, 27; 26, 30; 27, comparison_operator:is; 27, 28; 27, 29; 28, identifier:dowrite; 29, None; 30, block; 30, 31; 31, expression_statement; 31, 32; 32, assignment; 32, 33; 32, 34; 33, identifier:dowrite; 34, call; 34, 35; 34, 38; 35, attribute; 35, 36; 35, 37; 36, identifier:ut; 37, identifier:get_argflag; 38, argument_list; 38, 39; 39, tuple; 39, 40; 39, 41; 40, string:'-w'; 41, string:'--write'; 42, if_statement; 42, 43; 42, 46; 43, comparison_operator:is; 43, 44; 43, 45; 44, identifier:show_diff; 45, None; 46, block; 46, 47; 47, expression_statement; 47, 48; 48, assignment; 48, 49; 48, 50; 49, identifier:show_diff; 50, call; 50, 51; 50, 54; 51, attribute; 51, 52; 51, 53; 52, identifier:ut; 53, identifier:get_argflag; 54, argument_list; 54, 55; 55, string:'--diff'; 56, expression_statement; 56, 57; 57, assignment; 57, 58; 57, 59; 58, identifier:num_context_lines; 59, call; 59, 60; 59, 63; 60, attribute; 60, 61; 60, 62; 61, identifier:ut; 62, identifier:get_argval; 63, argument_list; 63, 64; 63, 65; 63, 68; 64, string:'--diff'; 65, keyword_argument; 65, 66; 65, 67; 66, identifier:type_; 67, identifier:int; 68, keyword_argument; 68, 69; 68, 70; 69, identifier:default; 70, None; 71, expression_statement; 71, 72; 72, assignment; 72, 73; 72, 74; 73, identifier:show_diff; 74, boolean_operator:or; 74, 75; 74, 76; 75, identifier:show_diff; 76, comparison_operator:is; 76, 77; 76, 78; 77, identifier:num_context_lines; 78, None; 79, expression_statement; 79, 80; 80, assignment; 80, 81; 80, 82; 81, identifier:num_context_lines; 82, call; 82, 83; 82, 86; 83, attribute; 83, 84; 83, 85; 84, identifier:ut; 85, identifier:get_argval; 86, argument_list; 86, 87; 86, 88; 86, 91; 87, string:'--diff'; 88, keyword_argument; 88, 89; 88, 90; 89, identifier:type_; 90, identifier:int; 91, keyword_argument; 91, 92; 91, 93; 92, identifier:default; 93, None; 94, if_statement; 94, 95; 94, 98; 95, comparison_operator:is; 95, 96; 95, 97; 96, identifier:fullprint; 97, None; 98, block; 98, 99; 99, expression_statement; 99, 100; 100, assignment; 100, 101; 100, 102; 101, identifier:fullprint; 102, True; 103, if_statement; 103, 104; 103, 107; 104, comparison_operator:is; 104, 105; 104, 106; 105, identifier:fullprint; 106, False; 107, block; 107, 108; 108, expression_statement; 108, 109; 109, assignment; 109, 110; 109, 111; 110, identifier:fullprint; 111, call; 111, 112; 111, 115; 112, attribute; 112, 113; 112, 114; 113, identifier:ut; 114, identifier:get_argflag; 115, argument_list; 115, 116; 116, string:'--print'; 117, expression_statement; 117, 118; 118, call; 118, 119; 118, 120; 119, identifier:print; 120, argument_list; 120, 121; 121, binary_operator:%; 121, 122; 121, 123; 122, string:'[autogen] Autogenerated %s...\n+---\n'; 123, tuple; 123, 124; 124, identifier:fpath; 125, if_statement; 125, 126; 125, 128; 126, not_operator; 126, 127; 127, identifier:dowrite; 128, block; 128, 129; 128, 155; 128, 160; 129, if_statement; 129, 130; 129, 131; 129, 147; 130, identifier:fullprint; 131, block; 131, 132; 131, 142; 132, expression_statement; 132, 133; 133, call; 133, 134; 133, 137; 134, attribute; 134, 135; 134, 136; 135, identifier:ut; 136, identifier:print_code; 137, argument_list; 137, 138; 137, 139; 138, identifier:autogen_text; 139, keyword_argument; 139, 140; 139, 141; 140, identifier:lexer_name; 141, identifier:codetype; 142, expression_statement; 142, 143; 143, call; 143, 144; 143, 145; 144, identifier:print; 145, argument_list; 145, 146; 146, string:'\nL___'; 147, else_clause; 147, 148; 148, block; 148, 149; 148, 154; 149, expression_statement; 149, 150; 150, call; 150, 151; 150, 152; 151, identifier:print; 152, argument_list; 152, 153; 153, string:'specify --print to write to stdout'; 154, pass_statement; 155, expression_statement; 155, 156; 156, call; 156, 157; 156, 158; 157, identifier:print; 158, argument_list; 158, 159; 159, string:'specify -w to write, or --diff to compare'; 160, expression_statement; 160, 161; 161, call; 161, 162; 161, 163; 162, identifier:print; 163, argument_list; 163, 164; 164, binary_operator:%; 164, 165; 164, 166; 165, string:'...would write to: %s'; 166, identifier:fpath; 167, if_statement; 167, 168; 167, 169; 167, 249; 168, identifier:show_diff; 169, block; 169, 170; 169, 241; 170, if_statement; 170, 171; 170, 180; 171, call; 171, 172; 171, 175; 172, attribute; 172, 173; 172, 174; 173, identifier:ut; 174, identifier:checkpath; 175, argument_list; 175, 176; 175, 177; 176, identifier:fpath; 177, keyword_argument; 177, 178; 177, 179; 178, identifier:verbose; 179, True; 180, block; 180, 181; 180, 190; 180, 203; 181, expression_statement; 181, 182; 182, assignment; 182, 183; 182, 184; 183, identifier:prev_text; 184, call; 184, 185; 184, 188; 185, attribute; 185, 186; 185, 187; 186, identifier:ut; 187, identifier:read_from; 188, argument_list; 188, 189; 189, identifier:fpath; 190, expression_statement; 190, 191; 191, assignment; 191, 192; 191, 193; 192, identifier:textdiff; 193, call; 193, 194; 193, 197; 194, attribute; 194, 195; 194, 196; 195, identifier:ut; 196, identifier:get_textdiff; 197, argument_list; 197, 198; 197, 199; 197, 200; 198, identifier:prev_text; 199, identifier:autogen_text; 200, keyword_argument; 200, 201; 200, 202; 201, identifier:num_context_lines; 202, identifier:num_context_lines; 203, try_statement; 203, 204; 203, 212; 204, block; 204, 205; 205, expression_statement; 205, 206; 206, call; 206, 207; 206, 210; 207, attribute; 207, 208; 207, 209; 208, identifier:ut; 209, identifier:print_difftext; 210, argument_list; 210, 211; 211, identifier:textdiff; 212, except_clause; 212, 213; 212, 214; 213, identifier:UnicodeDecodeError; 214, block; 214, 215; 214, 218; 214, 234; 215, import_statement; 215, 216; 216, dotted_name; 216, 217; 217, identifier:unicodedata; 218, expression_statement; 218, 219; 219, assignment; 219, 220; 219, 221; 220, identifier:textdiff; 221, call; 221, 222; 221, 231; 222, attribute; 222, 223; 222, 230; 223, call; 223, 224; 223, 227; 224, attribute; 224, 225; 224, 226; 225, identifier:unicodedata; 226, identifier:normalize; 227, argument_list; 227, 228; 227, 229; 228, string:'NFKD'; 229, identifier:textdiff; 230, identifier:encode; 231, argument_list; 231, 232; 231, 233; 232, string:'ascii'; 233, string:'ignore'; 234, expression_statement; 234, 235; 235, call; 235, 236; 235, 239; 236, attribute; 236, 237; 236, 238; 237, identifier:ut; 238, identifier:print_difftext; 239, argument_list; 239, 240; 240, identifier:textdiff; 241, if_statement; 241, 242; 241, 243; 242, identifier:dowrite; 243, block; 243, 244; 244, expression_statement; 244, 245; 245, call; 245, 246; 245, 247; 246, identifier:print; 247, argument_list; 247, 248; 248, string:'WARNING: Not writing. Remove --diff from command line'; 249, elif_clause; 249, 250; 249, 251; 250, identifier:dowrite; 251, block; 251, 252; 252, expression_statement; 252, 253; 253, call; 253, 254; 253, 257; 254, attribute; 254, 255; 254, 256; 255, identifier:ut; 256, identifier:write_to; 257, argument_list; 257, 258; 257, 259; 258, identifier:fpath; 259, identifier:autogen_text
def dump_autogen_code(fpath, autogen_text, codetype='python', fullprint=None, show_diff=None, dowrite=None): """ Helper that write a file if -w is given on command line, otherwise it just prints it out. It has the opption of comparing a diff to the file. """ import utool as ut if dowrite is None: dowrite = ut.get_argflag(('-w', '--write')) if show_diff is None: show_diff = ut.get_argflag('--diff') num_context_lines = ut.get_argval('--diff', type_=int, default=None) show_diff = show_diff or num_context_lines is not None num_context_lines = ut.get_argval('--diff', type_=int, default=None) if fullprint is None: fullprint = True if fullprint is False: fullprint = ut.get_argflag('--print') print('[autogen] Autogenerated %s...\n+---\n' % (fpath,)) if not dowrite: if fullprint: ut.print_code(autogen_text, lexer_name=codetype) print('\nL___') else: print('specify --print to write to stdout') pass print('specify -w to write, or --diff to compare') print('...would write to: %s' % fpath) if show_diff: if ut.checkpath(fpath, verbose=True): prev_text = ut.read_from(fpath) textdiff = ut.get_textdiff(prev_text, autogen_text, num_context_lines=num_context_lines) try: ut.print_difftext(textdiff) except UnicodeDecodeError: import unicodedata textdiff = unicodedata.normalize('NFKD', textdiff).encode('ascii', 'ignore') ut.print_difftext(textdiff) if dowrite: print('WARNING: Not writing. Remove --diff from command line') elif dowrite: ut.write_to(fpath, autogen_text)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 23; 2, function_name:make_default_docstr; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 3, 14; 3, 17; 3, 20; 4, identifier:func; 5, default_parameter; 5, 6; 5, 7; 6, identifier:with_args; 7, True; 8, default_parameter; 8, 9; 8, 10; 9, identifier:with_ret; 10, True; 11, default_parameter; 11, 12; 11, 13; 12, identifier:with_commandline; 13, True; 14, default_parameter; 14, 15; 14, 16; 15, identifier:with_example; 16, True; 17, default_parameter; 17, 18; 17, 19; 18, identifier:with_header; 19, False; 20, default_parameter; 20, 21; 20, 22; 21, identifier:with_debug; 22, False; 23, block; 23, 24; 23, 26; 23, 31; 23, 32; 23, 43; 23, 49; 23, 55; 23, 61; 23, 67; 23, 73; 23, 79; 23, 85; 23, 91; 23, 97; 23, 103; 23, 109; 23, 115; 23, 121; 23, 127; 23, 133; 23, 139; 23, 145; 23, 149; 23, 150; 23, 164; 23, 165; 23, 207; 23, 208; 23, 209; 23, 210; 23, 211; 23, 212; 23, 213; 23, 214; 23, 215; 23, 216; 23, 217; 23, 253; 23, 254; 23, 255; 23, 285; 23, 330; 23, 331; 23, 369; 23, 370; 23, 409; 23, 418; 23, 428; 24, expression_statement; 24, 25; 25, comment; 26, import_statement; 26, 27; 27, aliased_import; 27, 28; 27, 30; 28, dotted_name; 28, 29; 29, identifier:utool; 30, identifier:ut; 31, comment; 32, expression_statement; 32, 33; 33, assignment; 33, 34; 33, 35; 34, identifier:funcinfo; 35, call; 35, 36; 35, 41; 36, attribute; 36, 37; 36, 40; 37, attribute; 37, 38; 37, 39; 38, identifier:ut; 39, identifier:util_inspect; 40, identifier:infer_function_info; 41, argument_list; 41, 42; 42, identifier:func; 43, expression_statement; 43, 44; 44, assignment; 44, 45; 44, 46; 45, identifier:argname_list; 46, attribute; 46, 47; 46, 48; 47, identifier:funcinfo; 48, identifier:argname_list; 49, expression_statement; 49, 50; 50, assignment; 50, 51; 50, 52; 51, identifier:argtype_list; 52, attribute; 52, 53; 52, 54; 53, identifier:funcinfo; 54, identifier:argtype_list; 55, expression_statement; 55, 56; 56, assignment; 56, 57; 56, 58; 57, identifier:argdesc_list; 58, attribute; 58, 59; 58, 60; 59, identifier:funcinfo; 60, identifier:argdesc_list; 61, expression_statement; 61, 62; 62, assignment; 62, 63; 62, 64; 63, identifier:return_header; 64, attribute; 64, 65; 64, 66; 65, identifier:funcinfo; 66, identifier:return_header; 67, expression_statement; 67, 68; 68, assignment; 68, 69; 68, 70; 69, identifier:return_type; 70, attribute; 70, 71; 70, 72; 71, identifier:funcinfo; 72, identifier:return_type; 73, expression_statement; 73, 74; 74, assignment; 74, 75; 74, 76; 75, identifier:return_name; 76, attribute; 76, 77; 76, 78; 77, identifier:funcinfo; 78, identifier:return_name; 79, expression_statement; 79, 80; 80, assignment; 80, 81; 80, 82; 81, identifier:return_desc; 82, attribute; 82, 83; 82, 84; 83, identifier:funcinfo; 84, identifier:return_desc; 85, expression_statement; 85, 86; 86, assignment; 86, 87; 86, 88; 87, identifier:funcname; 88, attribute; 88, 89; 88, 90; 89, identifier:funcinfo; 90, identifier:funcname; 91, expression_statement; 91, 92; 92, assignment; 92, 93; 92, 94; 93, identifier:modname; 94, attribute; 94, 95; 94, 96; 95, identifier:funcinfo; 96, identifier:modname; 97, expression_statement; 97, 98; 98, assignment; 98, 99; 98, 100; 99, identifier:defaults; 100, attribute; 100, 101; 100, 102; 101, identifier:funcinfo; 102, identifier:defaults; 103, expression_statement; 103, 104; 104, assignment; 104, 105; 104, 106; 105, identifier:num_indent; 106, attribute; 106, 107; 106, 108; 107, identifier:funcinfo; 108, identifier:num_indent; 109, expression_statement; 109, 110; 110, assignment; 110, 111; 110, 112; 111, identifier:needs_surround; 112, attribute; 112, 113; 112, 114; 113, identifier:funcinfo; 114, identifier:needs_surround; 115, expression_statement; 115, 116; 116, assignment; 116, 117; 116, 118; 117, identifier:funcname; 118, attribute; 118, 119; 118, 120; 119, identifier:funcinfo; 120, identifier:funcname; 121, expression_statement; 121, 122; 122, assignment; 122, 123; 122, 124; 123, identifier:ismethod; 124, attribute; 124, 125; 124, 126; 125, identifier:funcinfo; 126, identifier:ismethod; 127, expression_statement; 127, 128; 128, assignment; 128, 129; 128, 130; 129, identifier:va_name; 130, attribute; 130, 131; 130, 132; 131, identifier:funcinfo; 132, identifier:va_name; 133, expression_statement; 133, 134; 134, assignment; 134, 135; 134, 136; 135, identifier:kw_name; 136, attribute; 136, 137; 136, 138; 137, identifier:funcinfo; 138, identifier:kw_name; 139, expression_statement; 139, 140; 140, assignment; 140, 141; 140, 142; 141, identifier:kw_keys; 142, attribute; 142, 143; 142, 144; 143, identifier:funcinfo; 144, identifier:kw_keys; 145, expression_statement; 145, 146; 146, assignment; 146, 147; 146, 148; 147, identifier:docstr_parts; 148, list:[]; 149, comment; 150, if_statement; 150, 151; 150, 152; 151, identifier:with_header; 152, block; 152, 153; 152, 157; 153, expression_statement; 153, 154; 154, assignment; 154, 155; 154, 156; 155, identifier:header_block; 156, identifier:funcname; 157, expression_statement; 157, 158; 158, call; 158, 159; 158, 162; 159, attribute; 159, 160; 159, 161; 160, identifier:docstr_parts; 161, identifier:append; 162, argument_list; 162, 163; 163, identifier:header_block; 164, comment; 165, if_statement; 165, 166; 165, 174; 166, boolean_operator:and; 166, 167; 166, 168; 167, identifier:with_args; 168, comparison_operator:>; 168, 169; 168, 173; 169, call; 169, 170; 169, 171; 170, identifier:len; 171, argument_list; 171, 172; 172, identifier:argname_list; 173, integer:0; 174, block; 174, 175; 174, 179; 174, 192; 174, 200; 175, expression_statement; 175, 176; 176, assignment; 176, 177; 176, 178; 177, identifier:argheader; 178, string:'Args'; 179, expression_statement; 179, 180; 180, assignment; 180, 181; 180, 182; 181, identifier:arg_docstr; 182, call; 182, 183; 182, 184; 183, identifier:make_args_docstr; 184, argument_list; 184, 185; 184, 186; 184, 187; 184, 188; 184, 189; 184, 190; 184, 191; 185, identifier:argname_list; 186, identifier:argtype_list; 187, identifier:argdesc_list; 188, identifier:ismethod; 189, identifier:va_name; 190, identifier:kw_name; 191, identifier:kw_keys; 192, expression_statement; 192, 193; 193, assignment; 193, 194; 193, 195; 194, identifier:argsblock; 195, call; 195, 196; 195, 197; 196, identifier:make_docstr_block; 197, argument_list; 197, 198; 197, 199; 198, identifier:argheader; 199, identifier:arg_docstr; 200, expression_statement; 200, 201; 201, call; 201, 202; 201, 205; 202, attribute; 202, 203; 202, 204; 203, identifier:docstr_parts; 204, identifier:append; 205, argument_list; 205, 206; 206, identifier:argsblock; 207, comment; 208, comment; 209, comment; 210, comment; 211, comment; 212, comment; 213, comment; 214, comment; 215, comment; 216, comment; 217, if_statement; 217, 218; 217, 223; 218, boolean_operator:and; 218, 219; 218, 220; 219, identifier:with_ret; 220, comparison_operator:is; 220, 221; 220, 222; 221, identifier:return_header; 222, None; 223, block; 223, 224; 224, if_statement; 224, 225; 224, 228; 225, comparison_operator:is; 225, 226; 225, 227; 226, identifier:return_header; 227, None; 228, block; 228, 229; 228, 238; 228, 246; 229, expression_statement; 229, 230; 230, assignment; 230, 231; 230, 232; 231, identifier:return_doctr; 232, call; 232, 233; 232, 234; 233, identifier:make_returns_or_yeilds_docstr; 234, argument_list; 234, 235; 234, 236; 234, 237; 235, identifier:return_type; 236, identifier:return_name; 237, identifier:return_desc; 238, expression_statement; 238, 239; 239, assignment; 239, 240; 239, 241; 240, identifier:returnblock; 241, call; 241, 242; 241, 243; 242, identifier:make_docstr_block; 243, argument_list; 243, 244; 243, 245; 244, identifier:return_header; 245, identifier:return_doctr; 246, expression_statement; 246, 247; 247, call; 247, 248; 247, 251; 248, attribute; 248, 249; 248, 250; 249, identifier:docstr_parts; 250, identifier:append; 251, argument_list; 251, 252; 252, identifier:returnblock; 253, comment; 254, comment; 255, if_statement; 255, 256; 255, 257; 256, identifier:with_commandline; 257, block; 257, 258; 257, 262; 257, 270; 257, 278; 258, expression_statement; 258, 259; 259, assignment; 259, 260; 259, 261; 260, identifier:cmdlineheader; 261, string:'CommandLine'; 262, expression_statement; 262, 263; 263, assignment; 263, 264; 263, 265; 264, identifier:cmdlinecode; 265, call; 265, 266; 265, 267; 266, identifier:make_cmdline_docstr; 267, argument_list; 267, 268; 267, 269; 268, identifier:funcname; 269, identifier:modname; 270, expression_statement; 270, 271; 271, assignment; 271, 272; 271, 273; 272, identifier:cmdlineblock; 273, call; 273, 274; 273, 275; 274, identifier:make_docstr_block; 275, argument_list; 275, 276; 275, 277; 276, identifier:cmdlineheader; 277, identifier:cmdlinecode; 278, expression_statement; 278, 279; 279, call; 279, 280; 279, 283; 280, attribute; 280, 281; 280, 282; 281, identifier:docstr_parts; 282, identifier:append; 283, argument_list; 283, 284; 284, identifier:cmdlineblock; 285, if_statement; 285, 286; 285, 287; 286, identifier:with_example; 287, block; 287, 288; 287, 292; 287, 305; 287, 315; 287, 323; 288, expression_statement; 288, 289; 289, assignment; 289, 290; 289, 291; 290, identifier:exampleheader; 291, string:'Example'; 292, expression_statement; 292, 293; 293, assignment; 293, 294; 293, 295; 294, identifier:examplecode; 295, call; 295, 296; 295, 297; 296, identifier:make_example_docstr; 297, argument_list; 297, 298; 297, 299; 297, 300; 297, 301; 297, 302; 297, 303; 297, 304; 298, identifier:funcname; 299, identifier:modname; 300, identifier:argname_list; 301, identifier:defaults; 302, identifier:return_type; 303, identifier:return_name; 304, identifier:ismethod; 305, expression_statement; 305, 306; 306, assignment; 306, 307; 306, 308; 307, identifier:examplecode_; 308, call; 308, 309; 308, 312; 309, attribute; 309, 310; 309, 311; 310, identifier:ut; 311, identifier:indent; 312, argument_list; 312, 313; 312, 314; 313, identifier:examplecode; 314, string:'>>> '; 315, expression_statement; 315, 316; 316, assignment; 316, 317; 316, 318; 317, identifier:exampleblock; 318, call; 318, 319; 318, 320; 319, identifier:make_docstr_block; 320, argument_list; 320, 321; 320, 322; 321, identifier:exampleheader; 322, identifier:examplecode_; 323, expression_statement; 323, 324; 324, call; 324, 325; 324, 328; 325, attribute; 325, 326; 325, 327; 326, identifier:docstr_parts; 327, identifier:append; 328, argument_list; 328, 329; 329, identifier:exampleblock; 330, comment; 331, if_statement; 331, 332; 331, 333; 332, identifier:with_debug; 333, block; 333, 334; 333, 338; 333, 354; 333, 362; 334, expression_statement; 334, 335; 335, assignment; 335, 336; 335, 337; 336, identifier:debugheader; 337, string:'Debug'; 338, expression_statement; 338, 339; 339, assignment; 339, 340; 339, 341; 340, identifier:debugblock; 341, call; 341, 342; 341, 350; 342, attribute; 342, 343; 342, 349; 343, call; 343, 344; 343, 347; 344, attribute; 344, 345; 344, 346; 345, identifier:ut; 346, identifier:codeblock; 347, argument_list; 347, 348; 348, string:''' num_indent = {num_indent} '''; 349, identifier:format; 350, argument_list; 350, 351; 351, keyword_argument; 351, 352; 351, 353; 352, identifier:num_indent; 353, identifier:num_indent; 354, expression_statement; 354, 355; 355, assignment; 355, 356; 355, 357; 356, identifier:debugblock; 357, call; 357, 358; 357, 359; 358, identifier:make_docstr_block; 359, argument_list; 359, 360; 359, 361; 360, identifier:debugheader; 361, identifier:debugblock; 362, expression_statement; 362, 363; 363, call; 363, 364; 363, 367; 364, attribute; 364, 365; 364, 366; 365, identifier:docstr_parts; 366, identifier:append; 367, argument_list; 367, 368; 368, identifier:debugblock; 369, comment; 370, if_statement; 370, 371; 370, 372; 370, 398; 371, identifier:needs_surround; 372, block; 372, 373; 372, 389; 373, expression_statement; 373, 374; 374, assignment; 374, 375; 374, 376; 375, identifier:docstr_parts; 376, binary_operator:+; 376, 377; 376, 387; 377, binary_operator:+; 377, 378; 377, 380; 378, list:['r"""']; 378, 379; 379, comment; 380, list:['\n\n'.join(docstr_parts)]; 380, 381; 381, call; 381, 382; 381, 385; 382, attribute; 382, 383; 382, 384; 383, string:'\n\n'; 384, identifier:join; 385, argument_list; 385, 386; 386, identifier:docstr_parts; 387, list:['"""']; 387, 388; 388, comment; 389, expression_statement; 389, 390; 390, assignment; 390, 391; 390, 392; 391, identifier:default_docstr; 392, call; 392, 393; 392, 396; 393, attribute; 393, 394; 393, 395; 394, string:'\n'; 395, identifier:join; 396, argument_list; 396, 397; 397, identifier:docstr_parts; 398, else_clause; 398, 399; 399, block; 399, 400; 400, expression_statement; 400, 401; 401, assignment; 401, 402; 401, 403; 402, identifier:default_docstr; 403, call; 403, 404; 403, 407; 404, attribute; 404, 405; 404, 406; 405, string:'\n\n'; 406, identifier:join; 407, argument_list; 407, 408; 408, identifier:docstr_parts; 409, expression_statement; 409, 410; 410, assignment; 410, 411; 410, 412; 411, identifier:docstr_indent; 412, binary_operator:*; 412, 413; 412, 414; 413, string:' '; 414, parenthesized_expression; 414, 415; 415, binary_operator:+; 415, 416; 415, 417; 416, identifier:num_indent; 417, integer:4; 418, expression_statement; 418, 419; 419, assignment; 419, 420; 419, 421; 420, identifier:default_docstr; 421, call; 421, 422; 421, 425; 422, attribute; 422, 423; 422, 424; 423, identifier:ut; 424, identifier:indent; 425, argument_list; 425, 426; 425, 427; 426, identifier:default_docstr; 427, identifier:docstr_indent; 428, return_statement; 428, 429; 429, identifier:default_docstr
def make_default_docstr(func, with_args=True, with_ret=True, with_commandline=True, with_example=True, with_header=False, with_debug=False): r""" Tries to make a sensible default docstr so the user can fill things in without typing too much # TODO: Interleave old documentation with new documentation Args: func (function): live python function with_args (bool): with_ret (bool): (Defaults to True) with_commandline (bool): (Defaults to True) with_example (bool): (Defaults to True) with_header (bool): (Defaults to False) with_debug (bool): (Defaults to False) Returns: tuple: (argname, val) Ignore: pass CommandLine: python -m utool.util_autogen --exec-make_default_docstr --show Example: >>> # ENABLE_DOCTEST >>> from utool.util_autogen import * # NOQA >>> import utool as ut >>> func = ut.make_default_docstr >>> #func = ut.make_args_docstr >>> #func = PythonStatement >>> func = auto_docstr >>> default_docstr = make_default_docstr(func) >>> result = str(default_docstr) >>> print(result) """ import utool as ut #from utool import util_inspect funcinfo = ut.util_inspect.infer_function_info(func) argname_list = funcinfo.argname_list argtype_list = funcinfo.argtype_list argdesc_list = funcinfo.argdesc_list return_header = funcinfo.return_header return_type = funcinfo.return_type return_name = funcinfo.return_name return_desc = funcinfo.return_desc funcname = funcinfo.funcname modname = funcinfo.modname defaults = funcinfo.defaults num_indent = funcinfo.num_indent needs_surround = funcinfo.needs_surround funcname = funcinfo.funcname ismethod = funcinfo.ismethod va_name = funcinfo.va_name kw_name = funcinfo.kw_name kw_keys = funcinfo.kw_keys docstr_parts = [] # Header part if with_header: header_block = funcname docstr_parts.append(header_block) # Args part if with_args and len(argname_list) > 0: argheader = 'Args' arg_docstr = make_args_docstr(argname_list, argtype_list, argdesc_list, ismethod, va_name, kw_name, kw_keys) argsblock = make_docstr_block(argheader, arg_docstr) docstr_parts.append(argsblock) # if False: # with_kw = with_args # if with_kw and len(kwarg_keys) > 0: # #ut.embed() # import textwrap # kwargs_docstr = ', '.join(kwarg_keys) # kwargs_docstr = '\n'.join(textwrap.wrap(kwargs_docstr)) # kwargsblock = make_docstr_block('Kwargs', kwargs_docstr) # docstr_parts.append(kwargsblock) # Return / Yeild part if with_ret and return_header is not None: if return_header is not None: return_doctr = make_returns_or_yeilds_docstr(return_type, return_name, return_desc) returnblock = make_docstr_block(return_header, return_doctr) docstr_parts.append(returnblock) # Example part # try to generate a simple and unit testable example if with_commandline: cmdlineheader = 'CommandLine' cmdlinecode = make_cmdline_docstr(funcname, modname) cmdlineblock = make_docstr_block(cmdlineheader, cmdlinecode) docstr_parts.append(cmdlineblock) if with_example: exampleheader = 'Example' examplecode = make_example_docstr(funcname, modname, argname_list, defaults, return_type, return_name, ismethod) examplecode_ = ut.indent(examplecode, '>>> ') exampleblock = make_docstr_block(exampleheader, examplecode_) docstr_parts.append(exampleblock) # DEBUG part (in case something goes wrong) if with_debug: debugheader = 'Debug' debugblock = ut.codeblock( ''' num_indent = {num_indent} ''' ).format(num_indent=num_indent) debugblock = make_docstr_block(debugheader, debugblock) docstr_parts.append(debugblock) # Enclosure / Indentation Parts if needs_surround: docstr_parts = ['r"""'] + ['\n\n'.join(docstr_parts)] + ['"""'] default_docstr = '\n'.join(docstr_parts) else: default_docstr = '\n\n'.join(docstr_parts) docstr_indent = ' ' * (num_indent + 4) default_docstr = ut.indent(default_docstr, docstr_indent) return default_docstr
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 7; 2, function_name:sort_protein_group; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:pgroup; 5, identifier:sortfunctions; 6, identifier:sortfunc_index; 7, block; 7, 8; 7, 10; 7, 14; 7, 23; 7, 27; 7, 67; 8, expression_statement; 8, 9; 9, comment; 10, expression_statement; 10, 11; 11, assignment; 11, 12; 11, 13; 12, identifier:pgroup_out; 13, list:[]; 14, expression_statement; 14, 15; 15, assignment; 15, 16; 15, 17; 16, identifier:subgroups; 17, call; 17, 18; 17, 21; 18, subscript; 18, 19; 18, 20; 19, identifier:sortfunctions; 20, identifier:sortfunc_index; 21, argument_list; 21, 22; 22, identifier:pgroup; 23, expression_statement; 23, 24; 24, augmented_assignment:+=; 24, 25; 24, 26; 25, identifier:sortfunc_index; 26, integer:1; 27, for_statement; 27, 28; 27, 29; 27, 30; 28, identifier:subgroup; 29, identifier:subgroups; 30, block; 30, 31; 31, if_statement; 31, 32; 31, 45; 31, 58; 32, boolean_operator:and; 32, 33; 32, 39; 33, comparison_operator:>; 33, 34; 33, 38; 34, call; 34, 35; 34, 36; 35, identifier:len; 36, argument_list; 36, 37; 37, identifier:subgroup; 38, integer:1; 39, comparison_operator:<; 39, 40; 39, 41; 40, identifier:sortfunc_index; 41, call; 41, 42; 41, 43; 42, identifier:len; 43, argument_list; 43, 44; 44, identifier:sortfunctions; 45, block; 45, 46; 46, expression_statement; 46, 47; 47, call; 47, 48; 47, 51; 48, attribute; 48, 49; 48, 50; 49, identifier:pgroup_out; 50, identifier:extend; 51, argument_list; 51, 52; 52, call; 52, 53; 52, 54; 53, identifier:sort_protein_group; 54, argument_list; 54, 55; 54, 56; 54, 57; 55, identifier:subgroup; 56, identifier:sortfunctions; 57, identifier:sortfunc_index; 58, else_clause; 58, 59; 59, block; 59, 60; 60, expression_statement; 60, 61; 61, call; 61, 62; 61, 65; 62, attribute; 62, 63; 62, 64; 63, identifier:pgroup_out; 64, identifier:extend; 65, argument_list; 65, 66; 66, identifier:subgroup; 67, return_statement; 67, 68; 68, identifier:pgroup_out
def sort_protein_group(pgroup, sortfunctions, sortfunc_index): """Recursive function that sorts protein group by a number of sorting functions.""" pgroup_out = [] subgroups = sortfunctions[sortfunc_index](pgroup) sortfunc_index += 1 for subgroup in subgroups: if len(subgroup) > 1 and sortfunc_index < len(sortfunctions): pgroup_out.extend(sort_protein_group(subgroup, sortfunctions, sortfunc_index)) else: pgroup_out.extend(subgroup) return pgroup_out
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:sort_amounts; 3, parameters; 3, 4; 3, 5; 4, identifier:proteins; 5, identifier:sort_index; 6, block; 6, 7; 6, 9; 6, 13; 6, 44; 7, expression_statement; 7, 8; 8, comment; 9, expression_statement; 9, 10; 10, assignment; 10, 11; 10, 12; 11, identifier:amounts; 12, dictionary; 13, for_statement; 13, 14; 13, 15; 13, 16; 14, identifier:protein; 15, identifier:proteins; 16, block; 16, 17; 16, 23; 17, expression_statement; 17, 18; 18, assignment; 18, 19; 18, 20; 19, identifier:amount_x_for_protein; 20, subscript; 20, 21; 20, 22; 21, identifier:protein; 22, identifier:sort_index; 23, try_statement; 23, 24; 23, 34; 24, block; 24, 25; 25, expression_statement; 25, 26; 26, call; 26, 27; 26, 32; 27, attribute; 27, 28; 27, 31; 28, subscript; 28, 29; 28, 30; 29, identifier:amounts; 30, identifier:amount_x_for_protein; 31, identifier:append; 32, argument_list; 32, 33; 33, identifier:protein; 34, except_clause; 34, 35; 34, 36; 35, identifier:KeyError; 36, block; 36, 37; 37, expression_statement; 37, 38; 38, assignment; 38, 39; 38, 42; 39, subscript; 39, 40; 39, 41; 40, identifier:amounts; 41, identifier:amount_x_for_protein; 42, list:[protein]; 42, 43; 43, identifier:protein; 44, return_statement; 44, 45; 45, list_comprehension; 45, 46; 45, 47; 46, identifier:v; 47, for_in_clause; 47, 48; 47, 51; 48, pattern_list; 48, 49; 48, 50; 49, identifier:k; 50, identifier:v; 51, call; 51, 52; 51, 53; 52, identifier:sorted; 53, argument_list; 53, 54; 53, 59; 54, call; 54, 55; 54, 58; 55, attribute; 55, 56; 55, 57; 56, identifier:amounts; 57, identifier:items; 58, argument_list; 59, keyword_argument; 59, 60; 59, 61; 60, identifier:reverse; 61, True
def sort_amounts(proteins, sort_index): """Generic function for sorting peptides and psms. Assumes a higher number is better for what is passed at sort_index position in protein.""" amounts = {} for protein in proteins: amount_x_for_protein = protein[sort_index] try: amounts[amount_x_for_protein].append(protein) except KeyError: amounts[amount_x_for_protein] = [protein] return [v for k, v in sorted(amounts.items(), reverse=True)]
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:compare_groups; 3, parameters; 3, 4; 3, 5; 4, identifier:true_groups; 5, identifier:pred_groups; 6, block; 6, 7; 6, 9; 6, 14; 6, 25; 6, 36; 6, 37; 6, 46; 6, 55; 6, 64; 6, 65; 6, 81; 6, 97; 6, 98; 6, 99; 6, 103; 6, 107; 6, 156; 6, 157; 6, 161; 6, 165; 6, 214; 6, 223; 6, 232; 6, 253; 6, 274; 6, 301; 7, expression_statement; 7, 8; 8, comment; 9, import_statement; 9, 10; 10, aliased_import; 10, 11; 10, 13; 11, dotted_name; 11, 12; 12, identifier:utool; 13, identifier:ut; 14, expression_statement; 14, 15; 15, assignment; 15, 16; 15, 17; 16, identifier:true; 17, set_comprehension; 17, 18; 17, 22; 18, call; 18, 19; 18, 20; 19, identifier:frozenset; 20, argument_list; 20, 21; 21, identifier:_group; 22, for_in_clause; 22, 23; 22, 24; 23, identifier:_group; 24, identifier:true_groups; 25, expression_statement; 25, 26; 26, assignment; 26, 27; 26, 28; 27, identifier:pred; 28, set_comprehension; 28, 29; 28, 33; 29, call; 29, 30; 29, 31; 30, identifier:frozenset; 31, argument_list; 31, 32; 32, identifier:_group; 33, for_in_clause; 33, 34; 33, 35; 34, identifier:_group; 35, identifier:pred_groups; 36, comment; 37, expression_statement; 37, 38; 38, assignment; 38, 39; 38, 40; 39, identifier:common; 40, call; 40, 41; 40, 44; 41, attribute; 41, 42; 41, 43; 42, identifier:true; 43, identifier:intersection; 44, argument_list; 44, 45; 45, identifier:pred; 46, expression_statement; 46, 47; 47, assignment; 47, 48; 47, 49; 48, identifier:true_sets; 49, call; 49, 50; 49, 53; 50, attribute; 50, 51; 50, 52; 51, identifier:true; 52, identifier:difference; 53, argument_list; 53, 54; 54, identifier:common; 55, expression_statement; 55, 56; 56, assignment; 56, 57; 56, 58; 57, identifier:pred_sets; 58, call; 58, 59; 58, 62; 59, attribute; 59, 60; 59, 61; 60, identifier:pred; 61, identifier:difference; 62, argument_list; 62, 63; 63, identifier:common; 64, comment; 65, expression_statement; 65, 66; 66, assignment; 66, 67; 66, 68; 67, identifier:pred_conn; 68, dictionary_comprehension; 68, 69; 68, 75; 68, 78; 69, pair; 69, 70; 69, 71; 70, identifier:p; 71, call; 71, 72; 71, 73; 72, identifier:frozenset; 73, argument_list; 73, 74; 74, identifier:ps; 75, for_in_clause; 75, 76; 75, 77; 76, identifier:ps; 77, identifier:pred; 78, for_in_clause; 78, 79; 78, 80; 79, identifier:p; 80, identifier:ps; 81, expression_statement; 81, 82; 82, assignment; 82, 83; 82, 84; 83, identifier:true_conn; 84, dictionary_comprehension; 84, 85; 84, 91; 84, 94; 85, pair; 85, 86; 85, 87; 86, identifier:t; 87, call; 87, 88; 87, 89; 88, identifier:frozenset; 89, argument_list; 89, 90; 90, identifier:ts; 91, for_in_clause; 91, 92; 91, 93; 92, identifier:ts; 93, identifier:true; 94, for_in_clause; 94, 95; 94, 96; 95, identifier:t; 96, identifier:ts; 97, comment; 98, comment; 99, expression_statement; 99, 100; 100, assignment; 100, 101; 100, 102; 101, identifier:pred_merges; 102, list:[]; 103, expression_statement; 103, 104; 104, assignment; 104, 105; 104, 106; 105, identifier:true_merges; 106, list:[]; 107, for_statement; 107, 108; 107, 109; 107, 110; 108, identifier:ts; 109, identifier:true_sets; 110, block; 110, 111; 110, 130; 111, expression_statement; 111, 112; 112, assignment; 112, 113; 112, 114; 113, identifier:ccs; 114, call; 114, 115; 114, 116; 115, identifier:set; 116, argument_list; 116, 117; 117, list_comprehension; 117, 118; 117, 127; 118, call; 118, 119; 118, 122; 119, attribute; 119, 120; 119, 121; 120, identifier:pred_conn; 121, identifier:get; 122, argument_list; 122, 123; 122, 124; 123, identifier:t; 124, call; 124, 125; 124, 126; 125, identifier:frozenset; 126, argument_list; 127, for_in_clause; 127, 128; 127, 129; 128, identifier:t; 129, identifier:ts; 130, if_statement; 130, 131; 130, 140; 130, 141; 131, comparison_operator:==; 131, 132; 131, 139; 132, call; 132, 133; 132, 136; 133, attribute; 133, 134; 133, 135; 134, identifier:frozenset; 135, identifier:union; 136, argument_list; 136, 137; 137, list_splat; 137, 138; 138, identifier:ccs; 139, identifier:ts; 140, comment; 141, block; 141, 142; 141, 149; 142, expression_statement; 142, 143; 143, call; 143, 144; 143, 147; 144, attribute; 144, 145; 144, 146; 145, identifier:pred_merges; 146, identifier:append; 147, argument_list; 147, 148; 148, identifier:ccs; 149, expression_statement; 149, 150; 150, call; 150, 151; 150, 154; 151, attribute; 151, 152; 151, 153; 152, identifier:true_merges; 153, identifier:append; 154, argument_list; 154, 155; 155, identifier:ts; 156, comment; 157, expression_statement; 157, 158; 158, assignment; 158, 159; 158, 160; 159, identifier:true_splits; 160, list:[]; 161, expression_statement; 161, 162; 162, assignment; 162, 163; 162, 164; 163, identifier:pred_splits; 164, list:[]; 165, for_statement; 165, 166; 165, 167; 165, 168; 166, identifier:ps; 167, identifier:pred_sets; 168, block; 168, 169; 168, 188; 169, expression_statement; 169, 170; 170, assignment; 170, 171; 170, 172; 171, identifier:ccs; 172, call; 172, 173; 172, 174; 173, identifier:set; 174, argument_list; 174, 175; 175, list_comprehension; 175, 176; 175, 185; 176, call; 176, 177; 176, 180; 177, attribute; 177, 178; 177, 179; 178, identifier:true_conn; 179, identifier:get; 180, argument_list; 180, 181; 180, 182; 181, identifier:p; 182, call; 182, 183; 182, 184; 183, identifier:frozenset; 184, argument_list; 185, for_in_clause; 185, 186; 185, 187; 186, identifier:p; 187, identifier:ps; 188, if_statement; 188, 189; 188, 198; 188, 199; 189, comparison_operator:==; 189, 190; 189, 197; 190, call; 190, 191; 190, 194; 191, attribute; 191, 192; 191, 193; 192, identifier:frozenset; 193, identifier:union; 194, argument_list; 194, 195; 195, list_splat; 195, 196; 196, identifier:ccs; 197, identifier:ps; 198, comment; 199, block; 199, 200; 199, 207; 200, expression_statement; 200, 201; 201, call; 201, 202; 201, 205; 202, attribute; 202, 203; 202, 204; 203, identifier:true_splits; 204, identifier:append; 205, argument_list; 205, 206; 206, identifier:ccs; 207, expression_statement; 207, 208; 208, call; 208, 209; 208, 212; 209, attribute; 209, 210; 209, 211; 210, identifier:pred_splits; 211, identifier:append; 212, argument_list; 212, 213; 213, identifier:ps; 214, expression_statement; 214, 215; 215, assignment; 215, 216; 215, 217; 216, identifier:pred_merges_flat; 217, call; 217, 218; 217, 221; 218, attribute; 218, 219; 218, 220; 219, identifier:ut; 220, identifier:flatten; 221, argument_list; 221, 222; 222, identifier:pred_merges; 223, expression_statement; 223, 224; 224, assignment; 224, 225; 224, 226; 225, identifier:true_splits_flat; 226, call; 226, 227; 226, 230; 227, attribute; 227, 228; 227, 229; 228, identifier:ut; 229, identifier:flatten; 230, argument_list; 230, 231; 231, identifier:true_splits; 232, expression_statement; 232, 233; 233, assignment; 233, 234; 233, 235; 234, identifier:pred_hybrid; 235, call; 235, 236; 235, 246; 236, attribute; 236, 237; 236, 245; 237, call; 237, 238; 237, 239; 238, identifier:frozenset; 239, argument_list; 239, 240; 240, call; 240, 241; 240, 242; 241, identifier:map; 242, argument_list; 242, 243; 242, 244; 243, identifier:frozenset; 244, identifier:pred_sets; 245, identifier:difference; 246, argument_list; 246, 247; 247, call; 247, 248; 247, 249; 248, identifier:set; 249, argument_list; 249, 250; 250, binary_operator:+; 250, 251; 250, 252; 251, identifier:pred_splits; 252, identifier:pred_merges_flat; 253, expression_statement; 253, 254; 254, assignment; 254, 255; 254, 256; 255, identifier:true_hybrid; 256, call; 256, 257; 256, 267; 257, attribute; 257, 258; 257, 266; 258, call; 258, 259; 258, 260; 259, identifier:frozenset; 260, argument_list; 260, 261; 261, call; 261, 262; 261, 263; 262, identifier:map; 263, argument_list; 263, 264; 263, 265; 264, identifier:frozenset; 265, identifier:true_sets; 266, identifier:difference; 267, argument_list; 267, 268; 268, call; 268, 269; 268, 270; 269, identifier:set; 270, argument_list; 270, 271; 271, binary_operator:+; 271, 272; 271, 273; 272, identifier:true_merges; 273, identifier:true_splits_flat; 274, expression_statement; 274, 275; 275, assignment; 275, 276; 275, 277; 276, identifier:comparisons; 277, dictionary; 277, 278; 277, 281; 277, 282; 277, 285; 277, 288; 277, 291; 277, 294; 277, 297; 277, 298; 278, pair; 278, 279; 278, 280; 279, string:'common'; 280, identifier:common; 281, comment; 282, pair; 282, 283; 282, 284; 283, string:'true_splits'; 284, identifier:true_splits; 285, pair; 285, 286; 285, 287; 286, string:'true_merges'; 287, identifier:true_merges; 288, pair; 288, 289; 288, 290; 289, string:'true_hybrid'; 290, identifier:true_hybrid; 291, pair; 291, 292; 291, 293; 292, string:'pred_splits'; 293, identifier:pred_splits; 294, pair; 294, 295; 294, 296; 295, string:'pred_merges'; 296, identifier:pred_merges; 297, comment; 298, pair; 298, 299; 298, 300; 299, string:'pred_hybrid'; 300, identifier:pred_hybrid; 301, return_statement; 301, 302; 302, identifier:comparisons
def compare_groups(true_groups, pred_groups): r""" Finds how predictions need to be modified to match the true grouping. Notes: pred_merges - the merges needed that would need to be done for the pred_groups to match true_groups. pred_hybrid - the hybrid split/merges needed that would need to be done for the pred_groups to match true_groups. Example: >>> # ENABLE_DOCTEST >>> from utool.util_alg import * # NOQA >>> import utool as ut >>> true_groups = [ >>> [20, 21], [22, 23], [1, 2], [12, 13, 14], [4], [5, 6, 3], [7, 8], >>> [9, 10, 11], [31, 32, 33, 34, 35], [41, 42, 43, 44], [45], [50] >>> ] >>> pred_groups = [ >>> [20, 21, 22, 23], [1, 2], [12], [13, 14], [3, 4], [5, 6,11], >>> [7], [8, 9], [10], [31, 32], [33, 34, 35], [41, 42, 43, 44, 45] >>> ] >>> comparisons = ut.compare_groups(true_groups, pred_groups) >>> print(comparisons) >>> result = ut.repr4(comparisons) >>> print(result) { 'common': {{1, 2}}, 'pred_hybrid': {{10}, {3, 4}, {5, 6, 11}, {7}, {8, 9}}, 'pred_merges': [{{12}, {13, 14}}, {{31, 32}, {33, 34, 35}}], 'pred_splits': [{20, 21, 22, 23}, {41, 42, 43, 44, 45}], 'true_hybrid': {{3, 5, 6}, {4}, {50}, {7, 8}, {9, 10, 11}}, 'true_merges': [{12, 13, 14}, {31, 32, 33, 34, 35}], 'true_splits': [{{20, 21}, {22, 23}}, {{41, 42, 43, 44}, {45}}], } """ import utool as ut true = {frozenset(_group) for _group in true_groups} pred = {frozenset(_group) for _group in pred_groups} # Find the groups that are exactly the same common = true.intersection(pred) true_sets = true.difference(common) pred_sets = pred.difference(common) # connected compoment lookups pred_conn = {p: frozenset(ps) for ps in pred for p in ps} true_conn = {t: frozenset(ts) for ts in true for t in ts} # How many predictions can be merged into perfect pieces? # For each true sets, find if it can be made via merging pred sets pred_merges = [] true_merges = [] for ts in true_sets: ccs = set([pred_conn.get(t, frozenset()) for t in ts]) if frozenset.union(*ccs) == ts: # This is a pure merge pred_merges.append(ccs) true_merges.append(ts) # How many predictions can be split into perfect pieces? true_splits = [] pred_splits = [] for ps in pred_sets: ccs = set([true_conn.get(p, frozenset()) for p in ps]) if frozenset.union(*ccs) == ps: # This is a pure merge true_splits.append(ccs) pred_splits.append(ps) pred_merges_flat = ut.flatten(pred_merges) true_splits_flat = ut.flatten(true_splits) pred_hybrid = frozenset(map(frozenset, pred_sets)).difference( set(pred_splits + pred_merges_flat)) true_hybrid = frozenset(map(frozenset, true_sets)).difference( set(true_merges + true_splits_flat)) comparisons = { 'common': common, # 'true_splits_flat': true_splits_flat, 'true_splits': true_splits, 'true_merges': true_merges, 'true_hybrid': true_hybrid, 'pred_splits': pred_splits, 'pred_merges': pred_merges, # 'pred_merges_flat': pred_merges_flat, 'pred_hybrid': pred_hybrid, } return comparisons
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 8; 2, function_name:colwise_diag_idxs; 3, parameters; 3, 4; 3, 5; 4, identifier:size; 5, default_parameter; 5, 6; 5, 7; 6, identifier:num; 7, integer:2; 8, block; 8, 9; 8, 11; 8, 12; 8, 13; 8, 14; 8, 19; 8, 39; 8, 40; 8, 41; 8, 74; 8, 75; 8, 76; 9, expression_statement; 9, 10; 10, comment; 11, comment; 12, comment; 13, comment; 14, import_statement; 14, 15; 15, aliased_import; 15, 16; 15, 18; 16, dotted_name; 16, 17; 17, identifier:utool; 18, identifier:ut; 19, expression_statement; 19, 20; 20, assignment; 20, 21; 20, 22; 21, identifier:diag_idxs; 22, call; 22, 23; 22, 26; 23, attribute; 23, 24; 23, 25; 24, identifier:ut; 25, identifier:iprod; 26, argument_list; 26, 27; 27, list_splat; 27, 28; 28, list_comprehension; 28, 29; 28, 33; 29, call; 29, 30; 29, 31; 30, identifier:range; 31, argument_list; 31, 32; 32, identifier:size; 33, for_in_clause; 33, 34; 33, 35; 34, identifier:_; 35, call; 35, 36; 35, 37; 36, identifier:range; 37, argument_list; 37, 38; 38, identifier:num; 39, comment; 40, comment; 41, expression_statement; 41, 42; 42, assignment; 42, 43; 42, 44; 43, identifier:upper_diag_idxs; 44, list_comprehension; 44, 45; 44, 52; 44, 55; 44, 73; 45, subscript; 45, 46; 45, 47; 46, identifier:tup; 47, slice; 47, 48; 47, 49; 47, 50; 48, colon; 49, colon; 50, unary_operator:-; 50, 51; 51, integer:1; 52, for_in_clause; 52, 53; 52, 54; 53, identifier:tup; 54, identifier:diag_idxs; 55, if_clause; 55, 56; 56, call; 56, 57; 56, 58; 57, identifier:all; 58, argument_list; 58, 59; 59, list_comprehension; 59, 60; 59, 63; 60, comparison_operator:>; 60, 61; 60, 62; 61, identifier:a; 62, identifier:b; 63, for_in_clause; 63, 64; 63, 67; 64, pattern_list; 64, 65; 64, 66; 65, identifier:a; 66, identifier:b; 67, call; 67, 68; 67, 71; 68, attribute; 68, 69; 68, 70; 69, identifier:ut; 70, identifier:itertwo; 71, argument_list; 71, 72; 72, identifier:tup; 73, comment; 74, comment; 75, comment; 76, return_statement; 76, 77; 77, identifier:upper_diag_idxs
def colwise_diag_idxs(size, num=2): r""" dont trust this implementation or this function name Args: size (int): Returns: ?: upper_diag_idxs CommandLine: python -m utool.util_alg --exec-colwise_diag_idxs --size=5 --num=2 python -m utool.util_alg --exec-colwise_diag_idxs --size=3 --num=3 Example: >>> # DISABLE_DOCTEST >>> from utool.util_alg import * # NOQA >>> size = ut.get_argval('--size', default=5) >>> num = ut.get_argval('--num', default=2) >>> mat = np.zeros([size] * num, dtype=np.int) >>> upper_diag_idxs = colwise_diag_idxs(size, num) >>> poses = np.array(upper_diag_idxs) >>> idxs = np.ravel_multi_index(poses.T, mat.shape) >>> print('poses.T =\n%s' % (ut.repr2(poses.T),)) >>> mat[tuple(poses.T)] = np.arange(1, len(poses) + 1) >>> print(mat) poses.T = np.array([[0, 0, 1, 0, 1, 2, 0, 1, 2, 3], [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]]) """ # diag_idxs = list(diagonalized_iter(size)) # upper_diag_idxs = [(r, c) for r, c in diag_idxs if r < c] # # diag_idxs = list(diagonalized_iter(size)) import utool as ut diag_idxs = ut.iprod(*[range(size) for _ in range(num)]) #diag_idxs = list(ut.iprod(range(size), range(size))) # this is pretty much a simple c ordering upper_diag_idxs = [ tup[::-1] for tup in diag_idxs if all([a > b for a, b in ut.itertwo(tup)]) #if all([a > b for a, b in ut.itertwo(tup[:2])]) ] #upper_diag_idxs = [(c, r) for r, c in diag_idxs if r > c] # # upper_diag_idxs = [(r, c) for r, c in diag_idxs if r > c] return upper_diag_idxs