I'm learning Python on VSCode, initially I had installed Python 3.9.2 64 bit on my Debian system, I arrived a part of the course where needed to use.
The following line of code:
id: str | None
Then Python started to say that "the alternative sintax for unions requires Python 3.10 o posterior.", then I installed 3.10.6 64 bits and 3.12.5 64 bits.
If I use one of the versions that that are equals to 3.10 or superior then the error of "syntax for unions" disappears, but then appears errors from som apis y/or modules that are imported previously are shown as errors, because they can't be imported, for example Pydantic.
I already checked that all the needed API's are installed.
UPDATE 07/09/2024:
The following functions are defined for a router in the api but Pylance reports that the "user" function remains hidden by another declaration of the same name
router.get("/{id}")
async def user(id: int):
return search_user(id)
# Query
@router.get("/")
async def user(id: int, name: str):
return search_user(id)
def search_user(id: int):
users = filter(lambda user: user.id == id, users_list)
try:
return list(users)[0]
except:
return {"error": "No se ha encontrado el usuario"}
How can solve this?
Syntax like
id: str | None
is only compatible with python3.10+. If you want to use it, you must use new python versions.
However, you can still use python3.9, but you will have to rewrite this line like
from typing import Optional
id: Optional[str]
or, another option
from typing import Union
id: Union[str, None]
If you want to upgrade to newer python versions (and I personally recommend it to use latest features), you should install newer versions of packages (pydantic; etc.), because old packages versions can be not compatible with new python versions.
Try creating new virtual environment (if you use them) and install latest packages versions (recommended way), or just use commands like pip install pydantic --upgrade
for all of your failing packages.
Probably, you will have to refactor your code. Some packages modules or functions were removed in latest versions (for example, if you have used pydantic 1.* and upgraded to pydantic 2.*, this package had a lot of changes). Check out failing messages and try to use new packages modules, that replaced deprecated ones. (If you don't want to deal with those refactors, you can always downgrade python back to 3.9 and use type annotations as I mentioned before).
If you will still have errors, provide concrete packages runtime/import failure messages on python 3.10/3.12, and we will try to fix them.