0

I have a class with a attribute.

I'm trying to check if the user pass the correct attribute though the API, however my statement always return true even the data didn't match the first condition. I even try to switch the condition and it still return true in the first condition

Is there a basic things I miss or was intended?

edit 1: switch the condition to prevent confusion, the function will always return 'wrong input' no matter what input even with empty string

My code:

import uvicorn
from pydantic import BaseModel
from fastapi import FastAPI, HTTPException


class Test_var(BaseModel):
    test_attr: str


app = FastAPI()


@app.post("/test_request/")
async def root(test_var: Test_var):
    data_validation(test_var)

def data_validation(test_var):
    if 'M' and 'G' not in test_var.test_attr:
        raise HTTPException( status_code = 422, detail = "wrong input")
    elif 'M' or 'G' in test_var.test_attr:
        print(test_var.test_attr)
        raise HTTPException(status_code = 422, detail = "correct input")
MatsLindh
  • 49,529
  • 4
  • 53
  • 84
Timework
  • 1
  • 1
  • `if 'M'` is always true. `or` doesn't work the way it does in English. – Mark Ransom Aug 02 '22 at 03:01
  • I'd answer this but I know it's a duplicate. – Mark Ransom Aug 02 '22 at 03:03
  • @MarkRansom yes i know about that but the you can literally switch both condition and it would still return 'wrong input" message – Timework Aug 02 '22 at 03:09
  • @MarkRansom i can pass the data without G or M or even empty string it would still return the same message – Timework Aug 02 '22 at 03:13
  • 1
    Obviously you *don't* know about that, but don't feel bad. It's probably the most common mistake made in Python. That statement is parsed as `if ('M') and ('G' not in test_var.test_attr)`, `and` has the same problem as `or`. – Mark Ransom Aug 02 '22 at 03:21
  • @MarkRansom ..... i hate my life........ i spend whole afternoon yesterday just to solve this issue, i though was a class issue and i forgot some basic properties for the class – Timework Aug 02 '22 at 03:27
  • Like I said, don't feel bad. Take comfort in this cartoon: https://xkcd.com/1053/ – Mark Ransom Aug 02 '22 at 03:35
  • Read the answer(s) at the duplicate question until you understand. You need to combine full expressions. – Mark Ransom Aug 02 '22 at 03:50

0 Answers0