Is there a simple way to wrap a built-in function for the whole package?
jfong at ms4.hinet.net
jfong at ms4.hinet.net
Thu Aug 1 21:18:10 EDT 2019
Cameron Simpson於 2019年8月2日星期五 UTC+8上午6時25分00秒寫道:
> On 31Jul2019 19:16, Jach Fong <jfong at ms4.hinet.net> wrote:
> >I get a package from Pypi. The package has many modules using built-in open() function. I like to redefine all the open() there with the default encoding 'utf-8', but not for code outside the package. Maybe I can put my def statement at the beginning of every module of this package, but just wondering is there a simple way of doing it?
>
> I would define something like this in the __init__.py file of the
> package (or in some utils.py file in the package):
>
> def open8(path):
> return open(path, encoding='utf-8')
>
> and just:
>
> from . import open8
>
> and use "open8" throughout the code instead of "open"?
>
> What not alias "open"? Because I would want it evident that in this code
> we're doing a slightly special flavour of open. By using a distinct name
> I avoid confusion about the unusual semantics.
>
> Cheers,
> Cameron Simpson <cs at cskk.id.au>
Instead of changing open() to open8() throughout the code, I prefer change it directly to open(encoding='utf-8'). Anyway, using "from . import open" is a good idea, thank you.
--Jach
More information about the Python-list
mailing list