else
/ elif
used after return
PYL-R1705141 await self.receive_chat_message(message)
142
143async def video_api_app(request):
144 if request.method == "GET":145 # Get the current state of the video API
146 return sanic.response.json({"chat_messages": video_api.chat_messages})
147 elif request.method == "POST":
141 await self.receive_chat_message(message)
142
143async def video_api_app(request):
144 if request.method == "GET":145 # Get the current state of the video API
146 return sanic.response.json({"chat_messages": video_api.chat_messages})
147 elif request.method == "POST":
145 room_name = request.match_info["room_name"]
146 user_id = request.match_info["user_id"]
147
148 if request.method == "POST":149 # Create an offer
150 sdp = await app.video_chats[room_name].create_offer()
151 return sanic.response.json({"sdp": sdp})
119 room_name = request.match_info["room_name"]
120 user_id = request.match_info["user_id"]
121
122 if request.method == "GET":123 # Get the current state of the video chat
124 video_chat = app.video_chats[room_name]
125 return sanic.response.json({"chat_messages": video_chat.chat_messages, "viewers": len(video_chat.viewers)})
145 room_name = request.match_info["room_name"]
146 user_id = request.match_info["user_id"]
147
148 if request.method == "POST":149 # Create an offer
150 sdp = await app.video_chats[room_name].create_offer()
151 return sanic.response.json({"sdp": sdp})
The use of else
or elif
becomes redundant and can be dropped if the last statement under the leading if
/ elif
block is a return
statement.
In the case of an elif
after return
, it can be written as a separate if
block.
For else
blocks after return
, the statements can be shifted out of else
. Please refer to the examples below for reference.
Refactoring the code this way can improve code-readability and make it easier to maintain.
def classify_number(x):
if x % 2 == 0:
return 'Even'
else:
return 'Odd'
def what_is_this_number(x):
if x % 2 == 0 and x >= 0:
return 'Even'
elif x % 2 == 0 and x < 0:
return 'Even and Negative'
elif x % 2 != 0 and x < 0:
return 'Odd and Negative.'
else:
return 'Odd'
def classify_number(x):
if x % 2 == 0:
return 'Even'
return 'Odd'
def what_is_this_number(x):
if x % 2 == 0 and x >= 0:
return 'Even'
if x % 2 == 0 and x < 0:
return 'Even and Negative'
if x % 2 != 0 and x < 0:
return 'Odd and Negative'
return 'Odd'