Is there a simple way to wrap a built-in function for the whole package?

Cameron Simpson cs at cskk.id.au
Thu Aug 1 18:24:41 EDT 2019


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>



More information about the Python-list mailing list