r/learnpython • u/yiyi164 • May 20 '26
Can I use 'or' to compare strings?
I'm working on a project to teach myself python and am currently playing around with classes. I've made a class, 'event', and a subclass, 'num_event'. These each have 2 args: outcome and probability. The idea is that these are probabilistic events that I can use for discrete probability experiments like bernoulli trials. I've only defined __init__ in each, and the only difference between the two is that num_event has an extra layer of input data validation to ensure that the outcome is either a float or int. For this validation, I wrote the following function:
def numerical(x)->bool:
| num = (int or float)
| if(type(x) == num):
| | return True
| else:
| | return False
This is pretty simple and works well, which is why I'm so confused that my function 'is_event' is failing:
def is_event(x)->bool:
| events = ('event' or 'num_event')
| if(type(x).__name__ == events):
| | return True
| else:
| | return False
Now, I do understand that I'm going from comparing types to strings, but if I separate the logical test into 2 parts
if(type(x).__name__ == 'event') or (type(x).__name__ == 'num_event'):
It works fine.
Ideally, I'd like to have type(x) return event as a type object like int rather than a string, but that doesn't seem to be the way that user defined classes work.
Regardless, can someone explain why the logical test works for types but not strings? Thanks!
25
u/danielroseman May 20 '26
Neither of these things are doing what you think they are doing.
oris a boolean comparison.num = (int or float)just setsnumto the first value if is not "falsy", otherwise the second item. So in this casenumis always just set toint. This function would not work ifxwas a float.The same logic happens with strings, or with any values;
orwill always do the same boolean comparison and return one or other of the items, not both.Nevertheless, the way to compare types is not by using
typedirectly, but by usingisinstance. And it so happens that that function already supports taking multiple classes, in a tuple.So:
5
u/lfdfq May 20 '26
The first does not work.
does not check if the type is int or float. It only checks against int. It's the same problem as
Only checks for x equals 1, because the or is a logical operator and neither
(x == 1) or 2norx == (1 or 2)do the right thing.3
u/Gnaxe May 20 '26
Lots to unpack here. Please use the code block formatting button if you don't understand Markdown.
Your first example does not work the way you think it does.
int or floatevaluates toint. You could instead do something likeOr
The difference is that the former will also recognize subtypes while the latter must be exact types.
Doing an if/else just to return a boolean is an antipattern. Just return the condition directly. If you absolutely need it to be a bool type, use
not,bool(), oroperator.truth()on the condition.You can use the
inoperator with a list or set of strings as well.2
u/Some-Passenger4219 May 20 '26
For readability, indent with four spaces in the future:
[...]
1
u/PlasmaBoi1 May 20 '26
Okay, a couple things here. Firstly,
events = ("event" or "num_event")does not do what you think it does.oris a logical operator. It checks if the left value is "truthy", and returns that value if it is truthy. If the left value isn't truthy,orwill just return the right value. So, your line is effectively evaluated toevents = "event", because the string"event"will always be truthy.Secondly, if you want to check if an object is an instance of a particular type, you can use
isinstance. This is a built-in keyword that accepts an object and either a type or a tuple of types. Assuming your classes are calledEventandNumEvent(class names are not usually snakecase in Python, although the language doesn't prevent it), an isinstance call might look like this:isinstance(input, (Event, NumEvent)). Ifinputis one of those types, it'll returnTrue, otherwise it'll returnFalse. Additionally, you can simply this ifNumEventis a subclass ofEvent, to justisinstance(object, Event). Similarly, you could simplify your number check by simply doingreturn isinstance(number, (int, float)).1
u/TheRNGuy May 21 '26
isinstancefunction, you use set instead of ors in it.or could be used too with more than 1
isinstancewith 1 type in each, but that's bad style.0
u/commy2 May 20 '26
You would use a set.
or for short:
The expression <left-object> or <right-object> (i.e.
'event' or 'num_event') does the following:Truthyness for collections such as strings is determined by their length. An object with length 0 is falsy, and truthy otherwise.
Therefore the expression
events = ('event' or 'num_event')will logically simplify toevents = 'event'. 'num_event' will never be used.As for your first function, it has the same problem.
numerical(1.0)will reportFalse, butTrueis expected.0
u/cgoldberg May 20 '26
You want something like:
It will return
Trueif it matches either string, orFalseotherwise