What variable type is returned from Open()?

Chris Angelico rosuav at gmail.com
Wed Apr 15 12:26:10 EDT 2020


On Thu, Apr 16, 2020 at 12:01 AM <dcwhatthe at gmail.com> wrote:
>
> Hi,
>
>
> As much as possible, I make use of optional type hints.  So if I know a function returns an integer, then I use
>
>
> this_number_i : int = GetThisNumber()
>
>
> But there's no 'file' type, so I'm not sure what to use as the type for the return value of an Open() function.
>
>
> config_file : file = open(config_file_s, "r")
>
>
> What type of variable should config_file (above) be declared as?
>

It returns a file-like object. Instead of annotating, just let the
type hinting system figure it out - you initialized it with the result
of an open() call, so it should be able to figure that out.

Python is not C, you do not need to declare all your variable types.

If you actually need a way to represent "file-like object" (maybe as a
parameter to some other function), there are tools for that in the
typing module, but just DON'T annotate every variable. Bad idea, will
cause you a maintenance headache and won't help anything.

ChrisA


More information about the Python-list mailing list