3 ms·
> assert(isinstance(arg, type)) The most irritating thing I've found is trying to write a function that accepts either a path or the raw contents of a file. P
by joshvm 8y ago
> assert(isinstance(arg, type))
The most irritating thing I've found is trying to write a function that accepts either a path or the raw contents of a file.
Python 3 makes this easy, you can check against string. Python 2 of course treats everything as a byte string.
In the end I just check the length of the input if the interpret identifies as python 2. If it's a short byte string, I assume it's a file name. Otherwise the minimum expected file size is almost certainly larger than the maximum path length.
- newen 8y agoWhy would you ever do that? Why would you even want a function that accepts either a file name or file contents when both are strings? What's so hard about defining a new function?
- mjw1007 8y agoOne common case where this is attractive is where you have a bunch of "public" functions built on top of each other, with the higher ones passing that parameter on and not otherwise caring what it is: high_level_function(src, ...) ... mid_level_function(src, ...) ... mid_level_function(src, ...) low_level_function(src, ...) ... low_level_function(src, ...) ... If you can make the low-level function generic one way or another, you avoid having to duplicate the higher-level functions. Another case is where there are two or more parameters that you want to be generic in this sense: if your only option is duplicating the function you can end up having to define inconveniently many variants.
- newen 8y agoYeah, that is convenient and I do that often. But I try to wrap the variables in different types depending on their source (e.g. whether it's a filename or file content) so that functions further down can disambiguate between variables explicitly.
- guidopallemans 8y agoAn example: pandas.read_csv https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html https://pandas.pydata.org/pandas-docs/stable/reference/api/p...
- makapuf 8y agoWhy not have clearer file, filename or data keyword arguments ? Or just file and call open or stringio if you have the file name or data ? Plenty of more explicit solutions.
- joshvm 8y agoLots of public APIs support this behaviour, it's convenient for users. For example numpy.fromfile will accept a file object or a string.