What variable type is returned from Open()?

dcwhatthe at gmail.com dcwhatthe at gmail.com
Thu Apr 16 12:22:14 EDT 2020


On Thursday, April 16, 2020 at 12:12:23 PM UTC-4, Richard Damon wrote:
> On 4/15/20 9:55 AM, dcw 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?
> >
> Running the simple test program in IDLE:
> 
> 
> f = open("TestFile.txt", "w")
> print (type(f))
> 
> I get the answer: <class '_io.TextIOWrapper'>
> 
> So that is the name of the type that is returned, at least for that
> call. One key thing to note is that it begins with a _, so that type is
> actually an implementation detail, subject to change. This isn't that
> strange in Python as normally you don't really need to know the type of
> an object, but what capabilities the object supports (most from its
> type, but some operations can be just added to the object). This is
> largely because Python is based on a concept call 'Duck-Typing', where
> it is more important if the object quacks like a duck then if it
> technically IS a duck. (And strangely, I believe you can have something
> that technically is a duck, but doesn't quack like one, as well as
> something totally unrelated to the duck type but quacks just like one).
> Files are such an animal, 'fileness' is not based on type, but on
> capability.
> 
> -- 
> Richard Damon

Ok, thanks.


More information about the Python-list mailing list