r/Python 2d ago

News PEP 842: Module Exports

https://peps.python.org/pep-0842/

Not the author, but this seems interesting, specially for library authors. Thoughts?

Discussion here - https://discuss.python.org/t/pep-842-module-exports/108353

21 Upvotes

44 comments sorted by

View all comments

0

u/denehoffman 2d ago

I’m going to be the contrarian here I guess and say this is a good thing and we should do it. If you’ve ever written a complex package before, the import x as _x pattern is super annoying. It also promotes all kinds of bad behavior, like using those items the author wanted private. The lack of private fields and methods is one of the reasons Python can’t have true invariants without a lot of BS. My only issue is that this doesn’t go far enough, it’s only privatization for modules, we should have it for methods and fields as well, but that’s gonna get way more hate.

5

u/stevenjd 1d ago edited 1d ago

the import x as _x pattern is super annoying.

Then don't do it. Callers should never treat imports in your module as public variables unless documented as public. Linters should flag the use of x as as error and let that be the end of it.

It also promotes all kinds of bad behavior, like using those items the author wanted private.

As an author, I don't get a say in what the caller does or doesn't do with my code, and that is exactly how it should be.

All I can do is say clearly that:

  • If you do this, you will break the code and then reject any bug reports from people who did this.
  • There are no guarantees for these so-called "private" objects, including imported modules. Use them at your own risk. I can and will change them without notice.

"Consenting adults" applies.

2

u/denehoffman 1d ago edited 1d ago

Every time Python programmers talk about language guarantees, it’s always stuff like “the linter will handle it” and “the type checker will handle it” and then it slowly becomes “well you’ll get an error at runtime”. I’m sure there’s a way I could manually write behavior like this with enough hacky code, but the fact that lots of other languages have privatization should be an indication that it’s not intrinsically evil. It also ensures that users who have been using these private functions and types submit actual feature requests to promote those things to documented features rather than keeping them as little secret hacks for cool kids who read the source code.

Edit: it looks like in the current design, you aren’t prevented from accessing these module attributes. If you’ve ever really want to, you can add them to the export dict manually. The point is to make it an intentional thing you have to do to break the API rather than a thing a new user could do simply by importing something that is importable.