Repository navigation
Discussion: What do we call the async versions of hip.get, hip.post, etc.? #168
Description
So everyone's used to being able to do:
import requests
response = requests.get(...)So I'm assuming we will also want to support:
import hip
response = hip.get(...)But what if you want to do an async get? If hip.get is already claimed for the sync version, then we can't use that for async gets.
There are three options I've thought about:
Option 1: Don't offer top-level async helpers at all. If you want to make async requests, you have to make an AsyncSession.
This is what I originally thought we'd want to do, because most users generally want to re-use connections, and especially b/c we want to support HTTP/2 in async mode, which requires background tasks and a shared connection pool. So pushing them towards sessions is the way to go, and we'd treat the no-session mode as a kind of simplified legacy interface for sync users only.
But... based on the discussion in #125, it sounds like we're going to be able to support HTTP/2 and shared connection pools even if users aren't explicitly using a session. So that makes the top-level hip.get-style helpers way more useful than before, and makes them equally useful in both sync and async mode. So maybe we want them after all!
Option 2: We could follow the same pattern as Python uses for e.g. __iter__ vs __aiter__, and have:
response = hip.get(...) # sync
response = await hip.aget(...) # asyncThis would work. There are some downsides though: it makes the async version feel a little more awkward and "second class". It means we either need to either rename the session methods too (await async_session.aget(...)), or else have an inconsistency (await hip.aget(...) / await async_session.get(...)). And if someone accidentally writes hip.get inside synchronous code, then it'll seem to work but cause nasty performance problems, as it blocks the whole main loop.
Also, making users pick between these two modes on a call-by-call basis just feels a bit wrong: generally either your whole program is sync, or else your whole program is async; it's not going to magically change between two lines in the same file.
Option 3: Use different namespaces. E.g.:
# Sync
import hip
response = hip.get(...)
# Async
import ahip
response = ahip.get(...)This seems pretty attractive. We could even remove the class name munging code, so instead of hip.Session and hip.AsyncSession, we'd just have hip.Session and async_hip.Session – make the two APIs completely identical except for the top-level namespace and the async/await annotations. And it has the nice property that if you're using async, you import the async namespace at the top of your file, and then you can't accidentally use the sync version; and the async version gets to use all the nice unqualified names like get.
It also makes life somewhat simpler for code that wants to build on top of hip, while using unasync to support both sync+async modes. You just do if ASYNC_MODE: import async_hip as hip; else import sync_hip as hip, and then the rest of your file uses hip and it just works in both modes. With "option 2" above you can also make this work, but you need a more sophisticated version of unasync that can munge aget → get, etc.
If we go down this road then we'll need to do some major bikeshedding to pick the names – hip vs async_hip? sync_hip versus async_hip? hip.sync versus hip.async_? (Unfortunately you can't have a module named async because it's a keyword :-(.) hip.s versus hip.a? This is kind of a second-order issue, because if separate namespaces are a bad idea, then we don't need to even think about names. But it's also kind of important, because my main hesitation with this approach is that all the "async hip" names look kind of ugly.
I guess we could even take this a step further and distribute hip and ahip as two separate packages in PyPI. Not sure if that's better or worse that bundling them together.
Activity
madsmtm commentedon Nov 29, 2019
What's to prevent making
work, by detecting with
sniffio(or likewise) whether the user is running async or not? (Not sure it's the best idea, just asking whether it's possible 😉)sethmlarson commentedon Nov 29, 2019
Is it possible to return an awaitable from a sync function? If so then that's feasible.
I bet we could do
typing.Callable[[...], typing.Union[SyncResponse, typing.Awaitable[AsyncResponse]]and that'd work nicely?njsmith commentedon Nov 29, 2019
But won't mypy then force you to do an explicit cast or
isinstancecheck every time you want to use the returned object?(Automagically switching between sync/async also makes me uncomfortable on vague grounds like "explicit is better than implicit". But I think the type issue is a more practical problem.)
sethmlarson commentedon Nov 29, 2019
That's my worry too, I'll experiment with how mypy handles this case.
sethmlarson commentedon Nov 29, 2019
Can confirm that mypy doesn't like the type annotation. Can't use overloads either because the return types are different.
oremanj commentedon Nov 29, 2019
Maybe put the async names in
hipand the sync names inhip.sync? And if you invoke the async names without an async event loop running, raise an error that points the user athip.sync. There are plenty of other HTTP libraries that are sync-first; maybe there's room for hip as one that's prominently async-first.hip.syncis the same number of characters asrequests, too...njsmith commentedon Dec 2, 2019
Hmm. It could work, but I'm a bit worried that it would send the message that we consider sync support to be an afterthought or second-class citizen. Of course we know that's not true, but I've noticed that people can be very sensitive to these kinds of signals, especially in that first 30 seconds looking at a project when they haven't decided yet whether to invest a whole 5 minutes in reading about it. And we want to position ourselves as the successor to urllib3/requests/etc., so it's important to communicate we care about those use cases.
Maybe we should make it
sync_hipandasync_hip, with a strong explicit convention that you door
? It's slightly weird, but at least it's just a single small dollop of weirdness that you can confront once and deal with, and it lets us use plain
hipwhen we want to talk about both versions at once. (Which will be a lot of the time, since all the API details are duplicated.)sethmlarson commentedon Dec 2, 2019
Hmm, I feel an aversion to having our top-level namespace be anything besides the package name. Currently I'm feeling
hip.SyncSession()/hip.AsyncSession(),hip.sync_request()/hip.async_request()?hip.a.request()andhip.s.request()being symmetrical also works for me and having all non-I/O related functions/members be imported at the top-levelhip. I'm kinda liking this one more and more due to how out of the way it is.njsmith commentedon Dec 2, 2019
Yeah, the different top-level namespaces is definitely "weird", but it does centralize all the weirdness in a single line at the top of the file... if we make people type
hip.sync_get(...)all the time then it's weird everywhere :-/Here's another idea: maybe we could get rid of the top-level
get/post/etc., if we made sessions really easy to use? So like the minimal example would be:The part that's super-weird-magical about this is that async operations always have to be done within a specific event loop. So in this version,
AsyncClientwould need to wait until the first time it's used before actually initializing anything (e.g. background workers)... and it would need some mechanism to catch cases like:In this case, two calls to
trio.runare using the sameAsyncClientobject, but they can't share sockets or any IO-related state, because of the separate event loops. So we'd need some strategy to deal with this.But of course we need something similar anyway for top-level operations like
hip.get; this just makes it more obvious.sethmlarson commentedon Dec 2, 2019
Edit: If we add
from . import a, sinto thehipnamespace then users will only need to callhip.s.Session()orhip.a.Session()once in their code unless they're creating sessions in multiple places, I feel like that case is rare? Usually I've only seen sessions created in one place in a codebase.I feel like users have come to expect something like a session-less
.request()method for toying around, I can tell you for certain I've never writtenrequests.Session()within an interactive console.sethmlarson commentedon Jan 16, 2020
So I'm now convinced that the two namespaces idea is the way forward due to removing the confusion between a sync / async painted object and a shared object between the sync and async namespaces. Here's the two that imo are the best contenders for names:
hip/ahipWe can reserve
ahipif we go this route to auto-installhip/ potentially in the future split the project into it's sync and async components?Pros
import hipgives you the right version that you want.Cons
ahipisn't really "anything", it's not immediately obvious that theameans async.Aesthetics
hip/async_hipHas very similar pros and cons as above. More verbose definitely but can hopefully be overcome with renaming imports (which is more common now, thanks data science community!).
If we were to use this method I'd suggest we recommend users do the following within documentation:
import async_hip as hipdhirschfeld commentedon Jan 17, 2020
How about having the async functions in the top-level
hipnamespace with the sync api mirrored inhip.sync?If a user wanted to use the sync interface they could then simply do:
sethmlarson commentedon Jan 17, 2020
The reason I think the sync functions should be default namespace is they're the ones you want when using a console, probably what most users will type first when experimenting.
dhirschfeld commentedon Jan 17, 2020
At least in ipython that's much less of a concern as you can await things in the repl with the
"magic" command.
e.g.
Just Works.
sethmlarson commentedon Jan 17, 2020
Discussed the IPython point with @njsmith and we agreed that the IPython case users probably still want the sync functions. There isn't much to gain from using async I/O within a REPL when the typical use-case is playing around and experimenting versus performance.
dhirschfeld commentedon Jan 17, 2020
I use the repl a lot to play around, but when I've got some working code I then copy & paste it into a script.
If you play around with the sync version you can no longer copy & paste without having to then annotate the code with async/await in all the right places. At least for me, async-ifying sync code is a bit of a whack-a-mole process until I've got the asyncs and awaits all correct. So I think there is actually a lot of value in an async repl!
But it's a totally valid position to not want to demote the sync version to a mere sub-package and
works just as well as
sethmlarson commentedon Jan 17, 2020
I'll definitely keep the async repl use-case in mind, so you are in favor of
hip/ahip? That's where I'm leaning as well.njsmith commentedon Jan 18, 2020
I think the nice thing about
ahipis that it doesn't require renaming at import time – obviously you can if you want, but typing one extra character isn't a big deal.And that means that when people are like, pasting code in chat to ask for help, we can see that this code has a bug (missing
await):In the possible world where both imports get renamed to
hip, the code becomes...and we have no idea whether there's a bug or not.
Other cases where this kind of clarity is helpful: pasting scripts from stackoverflow, tutorial text targeting users who aren't so clear on what async/await are, etc.
And realistically, most Python projects will be sync for the foreseeable future. No matter how sexy our new async libraries are, for most projects sync works just fine :-)
pquentin commentedon Jan 18, 2020
Another consideration here is unasync support. Say a library like Apache Libcloud wants to adopt unasync and use hip as an HTTP client, I guess "ahip" in _async folders becomes "hip" in _sync folders, but where is this transformation encoded?
RatanShreshtha commentedon Jan 18, 2020
What about something like
And both sync and async versions have similar APIs
njsmith commentedon Jan 18, 2020
I guess the two options are:
setup.pyIf we wanted to get fancy, I guess we could do some light AST analysis, and only enable the
ahip→hipreplacement for files that contain animport ahipnjsmith commentedon Jan 18, 2020
Annoyingly, this is actually impossible: since
asyncis a syntax keyword, Python refuses to let you use it as the name for a module.njsmith commentedon Jan 21, 2020
It sounds like we've pretty much converged on the
hip/ahipapproach... I wishahipwas prettier, but everything else has much more impactful downsides, so let's keep it simple.I claimed the name on PyPI: https://pypi.org/project/ahip/
(And the placeholder code is trivial, but I went ahead and pushed it to here: https://github.com/python-trio/ahip)
sethmlarson commentedon Jan 22, 2020
Closing this as decided, thanks everyone!
fixup async/await example after module rename #168 #213 (#230)