TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Designing Pythonic Library APIs

9 pointsby benhoytalmost 2 years ago

1 comment

Spivakalmost 2 years ago
There&#x27;s a lot here that is pretty general and not Python specific, let&#x27;s add some of those.<p>* Don&#x27;t use map&#x2F;filter&#x2F;select unless you have no other choice. Prefer comprehensions.<p>* If a loop can be expressed by a comprehension then it should be.<p>* If you can get away with a context manager, prefer that over destructors.<p>* Put your unit tests in classes rather than module_level functions.<p>* Have def main if __name__ == __main__: main() over entrypoints that have logic at the module level.<p>* Inheritance and multiple inheritance in Python is <i>fantastic</i>. Prefer it over composition.<p>* Remove the word lambda from your vocabulary.<p>* If possible avoid returning a list and instead prefer a generator.<p>* Replace &quot;for key in dict&quot; with &quot;for key, value in dict.items()&quot; as your default way of iterating over a dict.<p>* Whenever possible use pathlib over open and always specify the encoding for files opened in text mode.<p>* It&#x27;s more common to have &quot;def abstractfunc: pass&quot; than raise NotImplementedError.<p>* One file one class is for Java people, in Python pack it all in one file.<p>* obj.register(func) should probably be a decorator &quot;@obj.register def func: …&quot;<p>* Take advantage of truthy&#x2F;falsely values such as [] being false. Not if len(list) &gt; 0 but if list.<p>* Write a good __repr__ for every class.<p>* Take advantage of keyword only arguments to enforce subject.verb(object, adj1=2, adj2=2).<p>* If you leave black at the default of 80 characters someone will egg your GH profile.<p>* Add logging using the logging module and let the user if your lib decide if they&#x27;re useful or not.<p>* Abuse implicit string literal concatenation over str + str + str<p>* Formatting strings with % or .format is out. Either f-strings or the string.template library.<p>* Use StringIO over string concatenation.<p>* Raise an exception over returning Union[Ok, Err] or Optional[T].<p>* Log a warning over using the warnings module.<p>* Allow reading API keys from environment variables.<p>* from package import Thing is preferred unless the module in question is just a collection of functions.<p>* Use StrEnum over stringly typed function args.<p>* Do pass around bound methods even though it might feel wrong.
评论 #36387813 未加载
评论 #36387705 未加载