Best Python code snippet using lisa_python
strategy.py
Source:strategy.py
...63 self.x = msg.xmin64 self.y = msg.ymin65 self.w = msg.width66 self.h = msg.height67 #self.get_logger().info(('tolerance achieved'))68 #centerx = (2*x+w)/269 #centery = (2*y+h)/270 pass71 72 def hsv_center_check(self):73 ratio = float(self.h*1.0 / self.w)74 contours, hierarchy = cv.findContours(closing, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)75 for cntt in contours:76 cv.drawContours(res, cntt, -1, (0,255,255), 3) #yellow for all contours77 #area = cv.contourArea(cnt)78 #op = 079 if len(contours)!=0 :80 cnt = max(contours, key = cv.contourArea)81 area = cv.contourArea(cnt) 82 83 if area > 5000:84 self.get_logger().info(('currently ratio'+str(np.round(ratio,decimals=4))))85 if abs(ratio - self.pd_ratio) < 0.005:86 return True87 else:88 return False89 else :90 return False91 def check_z_distance(self):92 centery = (2*self.y+self.h)/293 if abs(centery-self.frame_height/2.0) < 1/10.0*self.frame_height:94 self.get_logger().info(('tolerance achieved'+str(int(abs(centery-self.frame_height/2.0)))))95 return True96 else:97 return False98 def z_adjust(self):99 centery = (2*self.y+self.h)/2100 self.z_adjust_vel = -(centery-self.frame_height/2.0)/self.frame_height *2101 mymsg = Twist()102 mymsg.linear.z = float(self.z_adjust_vel)103 self.gate_rotate_pub.publish(mymsg)104 105 def hover(self):106 msg = Twist()107 msg.angular.x = 0.0108 msg.linear.x = 0.0109 msg.angular.y = 0.0110 msg.linear.y = 0.0111 msg.angular.z = 0.0112 msg.linear.z = 0.0113 self.gate_rotate_pub.publish(msg)114 115 def check_az_distance(self):116 centerx = (2*self.x+self.w)/2117 if abs(centerx-self.frame_width/2.0) < 1/40.0*self.frame_width:118 self.get_logger().info(('tolerance achieved'+str(int(abs(centerx-self.frame_width/2.0)))))119 return True120 else:121 return False122 def az_adjust(self):123 centerx = (2*self.x+self.w)/2124 self.az_adjust_vel = -(centerx-self.frame_width/2.0)/self.frame_width/3.0125 mymsg = Twist()126 mymsg.angular.z = float(self.az_adjust_vel)127 self.gate_rotate_pub.publish(mymsg)128 def gate_rotate(self):129 self.ratio = float(self.h*1.0 / self.w)130 mymsg = Twist()131 mymsg.linear.x = 0.0132 mymsg.linear.z = 0.0133 # minimize134 diff = self.ratio - self.ratio_previous # first time diff>0135 if diff>0:136 self.rotate_dir = -self.rotate_dir # first time rotate_dir = -rotate_dir = 1.0137 mymsg.linear.y = self.gate_rotate_vel_y *self.rotate_dir138 mymsg.angular.z = self.gate_rotate_vel_az *self.rotate_dir139 self.gate_rotate_pub.publish(mymsg)140 self.ratio_previous = self.ratio141 pass142 def approach_complete_callback(self,req,res):143 self.get_logger().info(('tolerance achieved'))144 self.approach_flag = True145 return res146 def check_for_approach_two(self):147 148 149 pass150 def check_for_approach_flag(self):151 if self.approach_flag:152 #self.get_logger().info(('True'))153 self.approach_flag = False154 return True155 else:156 #self.get_logger().info(('False'))157 return False158 def flag_clean(self):159 self.approach_flag = False160 def send_takeoff_request(self): 161 start_request = TelloAction.Request()162 start_request.cmd = "takeoff"163 self.start_future = self.start_client.call_async(start_request)164 def send_rotate_request(self,flag):165 req = SetBool.Request()166 req.data = flag167 self.rotate_future = self.rotate_client.call_async(req)168 def send_forward_request(self,flag):169 req = SetBool.Request()170 req.data = flag171 self.forward_future = self.forward_client.call_async(req)172 def send_approach_request(self,flag):173 req = SetBool.Request()174 req.data = flag175 self.approach_future = self.approach_client.call_async(req)176 177 def send_flythrough_request(self):178 req = Empty.Request()179 self.flythrough_future = self.flythrough_client.call_async(req)180 def send_markerid_request(self,marker):181 req = MarkerId.Request()182 req.id = marker183 self.markerid_future = self.markerid_client.call_async(req)184 #def send_teleop_request(self,flag):185 # req = SetBool.Request()186 # req.data = flag187 # self.teleop_future = self.teleop_client.call_async(req)188 def hsv_check_center_horizontal(self):189 # rotate until x>1/10*frame.width, x+w<9/10*frame.width, abs(((x+w)+x)/2-frame.width)<1/10*frame.width 190 centerx = (2*self.x+self.w)/2191 centery = (2*self.y+self.h)/2192 if (self.x>1.0/10.0*self.frame_width)and((self.x+self.w)<9.0/10.0*self.frame_width)and((centerx-self.frame_width)<(1.0/10.0*self.frame_width)):193 self.get_logger().info('center testing approved')194 return True195 def hsv_check_center_height(self):196 # abs(h-desired_h)<1/20*frame.height197 if self.h>= 3.0/5.0/self.approach_ratio*self.frame_height:198 self.get_logger().info('distance testing approved')199 return True200def wait_for_takeoff_response(st):201 while rclpy.ok():202 rclpy.spin_once(st)203 if st.start_future.done():204 try:205 response = st.start_future.result()206 except Exception as e:207 st.get_logger().info((208 'Service call failed %r' % (e,)))209 210 break211 212def wait_rotate_response(st):213 while rclpy.ok():214 rclpy.spin_once(st)215 if st.rotate_future.done():216 try:217 response = st.rotate_future.result()218 except Exception as e:219 st.get_logger().info((220 'Service call failed %r' % (e,)))221 break222def wait_forward_response(st):223 while rclpy.ok():224 rclpy.spin_once(st)225 if st.forward_future.done():226 try:227 response = st.forward_future.result()228 except Exception as e:229 st.get_logger().info((230 'Service call failed %r' % (e,)))231 break232def wait_for_approach_response(st):233 while rclpy.ok():234 rclpy.spin_once(st)235 if st.approach_future.done():236 try:237 response = st.approach_future.result()238 except Exception as e:239 st.get_logger().info((240 'Service call failed %r' % (e,)))241 242 break243def wait_for_flythrough_response(st):244 while rclpy.ok():245 rclpy.spin_once(st)246 if st.flythrough_future.done():247 try:248 response = st.flythrough_future.result()249 except Exception as e:250 st.get_logger().info((251 'Service call failed %r' % (e,)))252 break253def wait_for_markerid_response(st):254 while rclpy.ok():255 rclpy.spin_once(st)256 if st.markerid_future.done():257 try:258 response = st.markerid_future.result()259 except Exception as e:260 st.get_logger().info((261 'Service call failed %r' % (e,)))262 break263#def wait_for_teleop_response(st):264# while rclpy.ok():265# rclpy.spin_once(st)266# if st.teleop_future.done():267# try:268# response = st.teleop_future.result()269# except Exception as e:270# st.get_logger().info((271# 'Service call failed %r' % (e,)))272# break273def search_for_AR_Tag(st,marker):274 find_artag1 = False275 while not find_artag1:276 try:277 now = rclpy.time.Time()278 st.trans = st.tf_buffer.lookup_transform(279 'tello_base',280 marker,281 now)282 find_artag1 = True283 except TransformException as ex:284 #st.get_logger().info(('not yet'))285 pass286 rclpy.spin_once(st)287def check_for_AR_Tag(st,marker):288 check_artag = False289 while not check_artag:290 try:291 now = rclpy.time.Time()292 st.trans = st.tf_buffer.lookup_transform(293 'tello_base',294 marker,295 now)296 check_for_artag = True297 except TransformException as ex:298 #st.get_logger().info(('not yet'))299 pass300 rclpy.spin_once(st)301def gate_artag_strategy(st,marker):302 # set marker_id for current_gate303 while not st.markerid_client.wait_for_service(timeout_sec=1.0):304 st.get_logger().info(('marker idservice not available, waiting again...'))305 st.send_markerid_request(marker)306 wait_for_markerid_response(st)307 st.get_logger().info(('currently finding Gate ..'+marker))308 # try to test ask 2 seconds, whether or not ARtag is found, if not, rotate again to find artag 309 # until st.check_for_approach_flag() True, break310 # y has steady error311 312 # rotate until find ARtag313 while not st.rotate_client.wait_for_service(timeout_sec=1.0):314 st.get_logger().info(('rotate service not available, waiting again...'))315 st.send_rotate_request(True)316 wait_rotate_response(st)317 st.get_logger().info(('start rotating, searching for artag now..'))318 search_for_AR_Tag(st,marker)319 st.get_logger().info(('ARtag1found, stop rotating..'))320 st.send_rotate_request(False)321 wait_rotate_response(st)322 st.get_logger().info(('successfully stopped'))323 st.get_logger().info("sofarsogood!")324 325 sleep(2)326 # approach ARtag327 st.get_logger().info("approaching ARtag!")328 while not st.approach_client.wait_for_service(timeout_sec=1.0):329 st.get_logger().info(('pid teleop service not available, waiting again...'))330 st.send_approach_request(True)331 wait_for_approach_response(st)332 while not st.check_for_approach_flag():333 rclpy.spin_once(st)334 sleep(0.5)335 #st.get_logger().info(('adjusting now...'))336 337 st.flag_clean()338 st.send_approach_request(False)339 wait_for_approach_response(st)340 st.get_logger().info("estimated approached,flythrough")341 342 sleep(5)343 #st.check_for_approach_two()344 #blind_fly_through345 346 st.get_logger().info("blind fly through ARtag!")347 while not st.flythrough_client.wait_for_service(timeout_sec=1.0):348 st.get_logger().info(('blind fly service not available, waiting again...'))349 st.send_flythrough_request()350 wait_for_flythrough_response(st)351 sleep(6)352 st.get_logger().info("already through ARtag!")353 pass354def hsv_gate_strategy(st):355 # stage 1: find the gate356 # rotate until x>1/10*frame.width, y+h<9/10*frame.width, abs(((x+w)+x)/2-frame.width)<1/10*frame.width 357 # call rotate service(SetBool), check for cv_pub in strategy358 359 st.get_logger().info(('try to find gate with hsv filter...'))360 while not st.rotate_client.wait_for_service(timeout_sec=1.0):361 st.get_logger().info(('rotate service not available, waiting again...'))362 st.send_rotate_request(True)363 wait_rotate_response(st)364 st.get_logger().info(('start rotating, searching for gate using hsv filter now..'))365 flag = False366 rclpy.spin_once(st)367 flag = st.hsv_check_center_horizontal()368 if st.hsv_check_center_horizontal():369 flag = True370 pass371 while not flag:372 rclpy.spin_once(st)373 flag = st.hsv_check_center_horizontal()374 pass375 376 st.get_logger().info(('Gate found, stop rotating..'))377 st.status_reset()378 st.send_rotate_request(False)379 wait_rotate_response(st)380 st.get_logger().info(('successfully stopped'))381 382 sleep(3)383 384 while not st.check_z_distance():385 rclpy.spin_once(st)386 st.z_adjust()387 st.get_logger().info(('z axis_adjusting..'))388 sleep(0.1)389 390 sleep(3)391 392 # keep height by making abs(((y+h)+y)/2 - frame.height)<1/10*frame.height393 # pid control, service disable tf_pub, enable pid_teleop394 # stage 2: approach the gate395 st.get_logger().info("approaching ARtag!")396 while not st.approach_client.wait_for_service(timeout_sec=1.0):397 st.get_logger().info(('pid teleop service not available, waiting again...'))398 st.send_approach_request(True)399 wait_for_approach_response(st)400 while(st.status==False):401 rclpy.spin_once(st)402 st.get_logger().info(('successfully through gate'))403 sleep(10)404 st.send_approach_request(False)405 # stage 2: approach the gate406 # slowly approch the gate until abs(h-desired_h)<1/20*frame.height407 #while not st.forward_client.wait_for_service(timeout_sec=1.0):408 # st.get_logger().info(('forward service not available, waiting again...'))409 #st.send_forward_request(True)410 #wait_forward_response(st)411 #st.get_logger().info(('start forwarding, searching for gate using hsv filter now..'))412 #flag = False413 #rclpy.spin_once(st)414 #flag = st.hsv_check_center_height()415 #if st.hsv_check_center_height():416 # flag = True417 # pass418 #while not flag:419 # rclpy.spin_once(st)420 # flag = st.hsv_check_center_height()421 # pass422 423 ##while not st.forward_client.wait_for_service(timeout_sec=1.0):424 # st.get_logger().info(('forward service not available, waiting again...'))425 #st.get_logger().info(('Gate approached, stop forwarding..'))426 #st.send_forward_request(False)427 #wait_forward_response(st)428 #st.get_logger().info(('successfully stopped'))429 430 ### az adjust431 #while not st.check_az_distance():432 # rclpy.spin_once(st)433 # st.az_adjust()434 # #st.get_logger().info(('z axis_adjusting..'))435 # sleep(0.1)436 437 #st.get_logger().info(('az successfully adjusted'))438 ## z adjust439 440 441 #st.get_logger().info(('z successfully adjusted 2'))442 #hoveriing443 #count = 0 444 #while count<200:445 # count=count+1446 # st.hover()447 # rclpy.spin_once(st)448 449 #st.get_logger().info(('sofarsogood3'))450 ### az adjust451 #while not st.check_az_distance():452 # rclpy.spin_once(st)453 # st.az_adjust()454 # #st.get_logger().info(('z axis_adjusting..'))455 # sleep(0.1)456 457 #st.get_logger().info(('az successfully adjusted'))458 #hoveriing459 #count = 0 460 #while count<200:461 ## count=count+1462 # st.hover()463 # rclpy.spin_once(st)464 # stage 3: center to the gate465 # rotate around the gate until abs(ratio-desired_ratio)<1/20*frame.height466 # strategy give out vel?467 468 #while not st.hsv_center_check():469 # st.gate_rotate()470 # rclpy.spin_once(st)471 # sleep(1/5)472 # st.get_logger().info(('rotating around the gate now'))473 474 #hoveriing475 # count = 0 476 # while count<200:477 # count=count+1478 # st.hover()479 # rclpy.spin_once(st)480 #st.get_logger().info(('center the gate successfully'))481 # stage 4: blindly fly through it482 #while not st.forward_client.wait_for_service(timeout_sec=1.0):483 # st.get_logger().info(('forward service not available, waiting again...'))484 #st.send_forward_request(True)485 #wait_forward_response(st)486 #st.get_logger().info(('start forwarding, searching for gate using hsv filter now..'))487 # done!488 #pass489 #sleep(20)490 #while not st.forward_client.wait_for_service(timeout_sec=1.0):491 # st.get_logger().info(('forward service not available, waiting again...'))492 #st.get_logger().info(('Gate approached, stop forwarding..'))493 #st.send_forward_request(False)494 #wait_forward_response(st)495 #st.get_logger().info(('successfully stopped'))496def main(args=None):497 rclpy.init(args=args) 498 st = strategy()499 st.get_logger().info(("preparing111"))500 sleep(5)501 #disable joy_stick_teleop502 #while not st.teleop_client.wait_for_service(timeout_sec=1.0): 503 # st.get_logger().info(('teleop service not available, waiting again...'))504 #st.send_teleop_request(False)505 #wait_for_teleop_response(st)506 #st.get_logger().info(('teleop disabled'))507 508 # take off509 510 while not st.start_client.wait_for_service(timeout_sec=1.0): 511 st.get_logger().info(('take off service not available, waiting again...'))512 st.send_takeoff_request()513 wait_for_takeoff_response(st)514 st.get_logger().info(('successfully taken off'))515 516 sleep(5)517 #gate_artag_strategy(st,'marker1')518 #st.get_logger().info("sofarsogood1!")519 520 #gate_artag_strategy(st,'marker2')521 #gate_artag_strategy(st,'marker3')522 #st.get_logger().info("sofarsogood2!")523 while(True):524 hsv_gate_strategy(st)525 526 # logic + 527 # if I lost the view of ARtag, I have to rotate to find it again528 #disable joy_stick_teleop529 #while not st.teleop_client.wait_for_service(timeout_sec=1.0): 530 # st.get_logger().info(('service not available, waiting again...'))531 #st.send_teleop_request(True)532 #wait_for_teleop_response(st)533 rclpy.spin(st)534 st.destroy_node()535 rclpy.shutdown()536if __name__ == '__main__':...
snake_tf2_listener.py
Source:snake_tf2_listener.py
...16 super().__init__('snake_tf2_frame_listener')17 # For the background color change18 self.color_client = self.create_client(SetParameters, '/sim/set_parameters')19 while not self.color_client.wait_for_service(timeout_sec=1.0):20 self.get_logger().info('service not available, waiting again...')21 self.req = None22 23 try:24 # Declare and acquire `target_frame` parameter25 self.declare_parameter('target_frame', 'turtle1')26 27 # The parameter received should be the adequate tail (one tail per body)28 self.target_frame = self.get_parameter(29 'target_frame').get_parameter_value().string_value30 except:31 self.get_logger().info(32 'Listener was not launched from launch file'33 )34 self.target_frame = 'turtle1'35 self.tf_buffer = Buffer()36 self.tf_listener = TransformListener(self.tf_buffer, self)37 # Create a client to spawn a turtle38 self.spawner = self.create_client(Spawn, 'spawn')39 # Boolean values to store the information40 # if the service for spawning turtle is available41 self.turtle_spawning_service_ready = False42 # if the turtle was successfully spawned43 self.body_spawned = False44 self.body_name = 'body1'45 self.start_position = [start_x, start_y, start_theta]46 # Create turtle2 velocity publisher47 self.publisher = self.create_publisher(Twist, f'{self.body_name}/cmd_vel', 1)48 # Call on_timer function every second49 # Maybe increase the rate50 self.timer = self.create_timer(0.01, self.on_timer)51 52 # Variable controlling if the snake has eaten the body53 self.body_eaten = False # Must be set to False54 55 def on_timer(self):56 # Store frame names in variables that will be used to57 # compute transformations58 from_frame_rel = self.target_frame59 to_frame_rel = self.body_name60 if self.turtle_spawning_service_ready:61 if self.body_spawned and self.body_eaten:62 # Look up for the transformation between target_frame and turtle2 frames63 # and send velocity commands for turtle2 to reach target_frame64 try:65 now = rclpy.time.Time()66 trans = self.tf_buffer.lookup_transform(67 to_frame_rel,68 from_frame_rel,69 now)70 except TransformException as ex:71 self.get_logger().info(72 f'EATEN: Could not transform {to_frame_rel} to {from_frame_rel}: {ex}')73 return74 except (LookupException, ConnectivityException, ExtrapolationException):75 self.get_logger().info('EATEN: transform not ready')76 return77 msg = Twist()78 # Diference between both Theta values79 # theta_diff = abs(1 - abs(trans.transform.rotation.w))80 ang_diff = math.atan2(81 trans.transform.translation.y,82 trans.transform.translation.x)83 84 dist = math.sqrt(85 abs(trans.transform.translation.x) ** 2 +86 abs(trans.transform.translation.y) ** 2)87 88 if ang_diff*180/math.pi >= 15 and dist > 0.1:89 90 scale_rotation_rate = 691 msg.angular.z = scale_rotation_rate * ang_diff92 93 scale_forward_speed = 1.594 msg.linear.x = scale_forward_speed * dist95 self.get_logger().info(96 f'Chasing target: ')97 self.get_logger().info(98 f'Linear Speed: {msg.linear.x}')99 self.get_logger().info(100 f'Angular Speed: {msg.angular.z}')101 self.get_logger().info(102 f'distance: {dist}')103 self.get_logger().info(104 f'Angle difference:{ang_diff*180/math.pi}')105 106 elif ang_diff*180/math.pi < 15 and dist > 0.1:107 108 scale_rotation_rate = 3109 msg.angular.z = scale_rotation_rate * ang_diff110 111 scale_forward_speed = 3112 msg.linear.x = scale_forward_speed * dist113 self.get_logger().info(114 f'Full Speed: ')115 self.get_logger().info(116 f'Linear Speed: {msg.linear.x}')117 self.get_logger().info(118 f'Angular Speed: {msg.angular.z}')119 self.get_logger().info(120 f'distance: {dist}')121 self.get_logger().info(122 f'Angle difference:{ang_diff*180/math.pi}')123 else:124 self.get_logger().info(125 f'STOP target is close: ')126 self.get_logger().info(127 f'Linear Speed: {msg.linear.x}')128 self.get_logger().info(129 f'Angular Speed: {msg.angular.z}')130 self.get_logger().info(131 f'distance: {dist}')132 self.get_logger().info(133 f'Angle difference:{ang_diff*180/math.pi}')134 135 self.publisher.publish(msg)136 137 138 elif not self.body_spawned:139 if self.result.done():140 self.get_logger().info(141 f'Successfully spawned {self.result.result().name}')142 self.body_spawned = True143 else:144 self.get_logger().info('Spawn is not finished')145 146 elif not self.body_eaten: 147 try:148 now = rclpy.time.Time()149 trans = self.tf_buffer.lookup_transform(150 to_frame_rel,151 from_frame_rel,152 now)153 154 distance = math.sqrt(155 abs(trans.transform.translation.x**2) + 156 abs(trans.transform.translation.y**2))157 # self.get_logger().info(158 # f'current distance to {self.body_name} is {distance} m')159 160 if distance < 1:161 self.body_eaten = True162 self.get_logger().info163 (f'Piece {self.body_name} EATEN, ÃAM ÃAM')164 self.change_background_color()165 166 except TransformException as ex:167 self.get_logger().info(168 f'NOT EATEN: Could not transform {to_frame_rel} to {from_frame_rel}: {ex}')169 return170 except (LookupException, ConnectivityException, ExtrapolationException):171 self.get_logger().info('NOT EATEN: transform not ready')172 return173 else:174 spawn_result = self.body_spawner()175 if spawn_result is not None:176 self.result = spawn_result177 def body_spawner(self):178 if self.spawner.service_is_ready():179 # Initialize request with turtle name and coordinates180 # Note that x, y and theta are defined as floats in turtlesim/srv/Spawn181 request = Spawn.Request()182 request.name = 'body1'183 if self.start_position[0]:184 request.x = self.start_position[0]185 self.start_position[0] = None # So this only happens for the first turtle186 self.get_logger().info(187 f'Given starting point X: {request.x}'188 )189 else:190 request.x = random.uniform(1, 19)191 self.get_logger().info(192 f'Random starting point X: {request.x}'193 )194 195 if self.start_position[1]:196 request.y = self.start_position[1]197 self.start_position[1] = None # So this only happens for the first turtle198 self.get_logger().info(199 f'Given starting point Y: {request.y}'200 )201 else:202 request.y = random.uniform(1, 19)203 self.get_logger().info(204 f'Random starting point Y: {request.y}'205 )206 207 if self.start_position[2]:208 request.theta = self.start_position[2]209 self.start_position[2] = None # So this only happens for the first turtle210 self.get_logger().info(211 f'Given starting Angle: {request.theta*180/math.pi}'212 )213 else:214 request.theta = random.uniform(-2*3.14, 2*3.14)215 self.get_logger().info(216 f'Random starting Angle: {request.theta*180/math.pi}'217 )218 219 # Call request and spawns turtle in result220 result = self.spawner.call_async(request)221 222 print(dir(result)) # debug223 224 self.turtle_spawning_service_ready = True225 return result226 else:227 # Check if the service is ready228 self.get_logger().info('Body spawner is not ready')229 return None230 231 def change_background_color(self, r=None, g=None, b=None):232 self.req = SetParameters.Request()233 param = Parameter()234 param.name = "background_r"235 param.value.type = ParameterType.PARAMETER_INTEGER236 if r:237 param.value.integer_value = r238 else:239 param.value.integer_value = random.randint(0,255)240 self.req.parameters.append(param)241 param = Parameter()242 param.name = "background_g"243 param.value.type = ParameterType.PARAMETER_INTEGER244 if g:245 param.value.integer_value = g246 else:247 param.value.integer_value = random.randint(0,255)248 self.req.parameters.append(param)249 250 param = Parameter()251 param.name = "background_b"252 param.value.type = ParameterType.PARAMETER_INTEGER253 if b:254 param.value.integer_value = b255 else:256 param.value.integer_value = random.randint(0,255)257 self.req.parameters.append(param)258 self.future = self.color_client.call_async(self.req)259 self.get_logger().info('client request sent')260 261 262def main():263 rclpy.init()264 node = FrameListener()265 try:266 rclpy.spin(node)267 except KeyboardInterrupt:268 pass...
task_11_1_once.py
Source:task_11_1_once.py
...12 wrapper.has_run = False13 print(f'id of function {id(wrapper())} name = {wrapper.__name__}')14 return wrapper15@once16def get_logger():17 return [1, 2, 3] * 218'''19### this== ### get_logger = once(get_logger)20print(get_logger.result, get_logger.has_run)21print('*' * 80)22'''23assert id(get_logger()) == id(get_logger()), "Not equal"24print('SUCCESS')25print(f'get_logger: {id(get_logger())} {id(get_logger())}')26print(f'get_logger: {id(get_logger())} {id(get_logger())}')27get_logger.has_run = False28print(f'get_logger: {id(get_logger())} {id(get_logger())}')29assert id(get_logger()) == id(get_logger()), "Not equal"30print('SUCCESS')31result = get_logger()32result.append(42)33print(result)...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!