pytransitions库get_triggers()返回结果不符合预期问题咨询
get_triggers() in pytransitions Finite State Machine Let's figure out why you're not getting the expected output from get_triggers() and fix it up. First, let's start with a working example that matches your transition setup—this will help you compare against your code.
Working Example Code
from transitions import Machine # Your transition definition (unchanged) transitions = [ {'trigger': 'melt', 'source': 'solid', 'dest': 'liquid'}, {'trigger': 'evaporate', 'source': 'liquid', 'dest': 'gas'}, {'trigger': 'sublimate', 'source': 'solid', 'dest': 'gas'}, {'trigger': 'ionize', 'source': 'gas', 'dest': 'plasma'} ] # A simple model class to attach the state machine to class Matter: pass # Initialize the state machine with your transitions and an initial state matter = Matter() machine = Machine(model=matter, transitions=transitions, initial='solid') # Get triggers for specific states print(machine.get_triggers('solid')) # Output: ['melt', 'sublimate'] print(matter.get_triggers('liquid')) # You can also call it directly on the model instance
Common Issues That Cause Unexpected get_triggers() Output
Here are the most likely reasons your call isn't working as expected:
You didn't specify an initial state or check the current state
If you omit theinitialparameter when creating theMachine, your model won't have a default state. Callingget_triggers()without a state argument will return triggers for the current state (which might beNone, resulting in an empty list). Always verify your model's current state withprint(matter.state)first.You're calling
get_triggers()without a state parameter
When you callget_triggers()without passing a state name, it returns triggers for the model's current state, not all states or a specific one you had in mind. For example, if your model is in thegasstate,get_triggers()will only return['ionize'].State name mismatch (case-sensitive!)
pytransitions treats state names as case-sensitive. If you callget_triggers('Solid')instead ofget_triggers('solid'), you'll get an empty list because the state doesn't exist. Double-check that the state name you pass exactly matches what's in your transition definitions.Your model isn't properly attached to the state machine
If you forgot to passmodel=matterwhen initializingMachine, or if you're using a model that wasn't bound to the state machine, calls toget_triggers()won't have access to your transition data. Make sure the model instance is linked during Machine setup.
Quick Debugging Steps
- Run
print(matter.state)to confirm your model's current state. - Verify that the state name you pass to
get_triggers()is spelled exactly (including case) as in your transitions. - Ensure your
Machineinitialization includes both themodelandtransitionsparameters, plus aninitialstate if you need a starting point.
内容的提问来源于stack exchange,提问作者Ramaq

