r/VisualStudioCode • u/mattl33 • Oct 27 '23
Pylance in VSC not recognizing custom python builtins
I can't quite figure this one out yet so I thought I'd try here. This is my first time trying to do anything with builtins but here's the issue:
I have a large-ish application of about 100 files and want to use python's IceCream module to provide a nice --debug option. I don't want to import icecream everywhere and they provide a way to do that via their install() function in the entry point file. This does what it's supposed to and there's no issues there, except that I can't get pylance to recognize that "ic" is defined in other files besides where install() is called.
main.py:
from icecream import ic
from icecream import install
install()
some_other_file.py:
from thing import func
ic() <- pylance complains: "ic" is not defined
1
u/BobtheBirdOfPrey Aug 13 '24
I faced the same issue and found a solution.
Create a __builtins__.pyi inside a typings folder. Then change python.analysis.stubPath to point to the typings folder.
__builtins__.pyi tells pylance that everything defined there is a python built-in. Inside __builtins__.pyi, define the call to icecream's ic.
from collections.abc import Iterable
from typing import Any
def ic(*args: Iterable) -> tuple[Any, ...] | None: ...Remember that this is just a typing definition, so you still have to install icecream.
try:
from icecream import install
install()
except ImportError:
__builtins__["ic"] = lambda *a: None if not a else a[0] if len(a) == 1 else aThis will try to import and set icecream as a built-in, and if it is not installed, it sets ic as the default function as defined by icecream.
This solved my issues with pylance and vscode, but I also use ruff and it still said that ic isn't defined. I had to add an option in my ruff.toml
builtins = ['ic']Now it also sees ic as a built-in.
1
u/sovata8 Mar 07 '26
It's an old thread but I stumbled on it from a google search - so in case anyone finds this useful:
I solved it by doing this:
At the root of the project I create a folder typings and inside it - a file __builtins__.pyi.
The file contains:
from typing import Any
# Tell Pylance that 'myfunc' exists everywhere and can be anything.
myfunc: AnyIt then works fine at call-sites, no warnings and no need for # type: ignore.
Note that in the one place the builtin is actually set, I still get the warning.
There we can do either:
builtins.myfunc = <...> # type: ignore
or
setattr(builtins, 'myfunc', <...>)
1
u/PhotographicCutout Feb 18 '24
Did you manage to resolve this? I'm facing the exact same issue