Python中_的含义解析及OpenAI Gym step函数用_的优势探讨
Python中下划线“_”的含义及在OpenAI Gym中的用法
Let's break down your questions clearly, starting with the general role of underscores in Python, then focusing on the specific use case in your OpenAI Gym code.
1. Common meanings of "_" in Python
The underscore is a flexible, convention-driven character in Python with a few key uses:
- Store last result in interactive mode: In Python's shell,
_automatically holds the output of your last executed expression. For example:>>> 10 * 5 50 >>> _ 50 - Ignore unused values: This is the most relevant case for your code. When unpacking values (like from a function return),
_signals that we don't need that specific value. It's a widely accepted community convention that makes code instantly readable—anyone seeing_knows that value is intentionally unused. - Signal internal-use variables: A single underscore prefix (e.g.,
_internal_var) tells other developers that a variable or method is meant for internal use only. Python doesn't enforce privacy here, but it's a respected hint. - Special method naming: Double underscores (e.g.,
__init__,__str__) are used for "dunder" methods (special built-in functions) and name mangling, but that's a separate topic from your question.
2. The "_" in OpenAI Gym's step() function
First, let's clarify what env.step(action) returns: it gives a 4-value tuple:
observation: The environment's new state after taking the actionreward: The reward earned for the actiondone: A boolean flag indicating if the episode has endedinfo: Extra diagnostic data (like debug stats) that's often unnecessary for basic testing or training
In your example code:
import gym env = gym.make('CartPole-v0') for i_episode in range(20): observation = env.reset() for t in range(100): env.render() print(observation) action = env.action_space.sample() observation, reward, done, _ = env.step(action) # The "_" here if done: print("Episode finished after {} timesteps".format(t+1)) break
The _ is explicitly catching the info value without assigning it a meaningful name. Since you don't use info anywhere in your code, this is exactly the scenario the underscore is designed for.
3. Why use "_" instead of another name?
- Better readability: It's a universal Python convention. Any developer reading your code will immediately understand that this value is unused, whereas a random name like
temporextra_datawould require a moment to confirm it's not needed. - Avoids IDE warnings: Most code editors (like VS Code, PyCharm) flag unused variables with warnings. Using
_tells the editor you intentionally aren't using this value, so no unnecessary alerts pop up. - Cleaner code: It eliminates the need to invent a throwaway variable name, keeping your code concise and focused on the values you actually care about.
内容的提问来源于stack exchange,提问作者Yograj Singh Mandloi
相关产品推荐
相关产品推荐

