title: Async SQLAlchemy Session: Commit using AsyncSession() or AsyncSession?
body: <p>I am starting to use <code>AsyncSession</code> from <code>sqlalchemy</code> in a <code>asyncio</code> app. However, when assigning an <code>AsyncSession</code> object to a class like <code>Foo</code> (<a href="https://docs.sqlalchemy.org/en/14/orm/extensions/asyncio.html#using-asyncio-scoped-session" rel="nofollow noreferrer">based on official docs</a>) and <code>Bar</code> below, is there any difference between doing it in the following 2 ways?</p>
  <pre><code>from asyncio import current_task
  
  from sqlalchemy.orm import sessionmaker
  from sqlalchemy.ext.asyncio import async_scoped_session
  from sqlalchemy.ext.asyncio import AsyncSession
  
  async_session_factory = sessionmaker(some_async_engine, class_=_AsyncSession)
  AsyncSession = async_scoped_session(async_session_factory, scopefunc=current_task)
  
  
  class Foo:
      # https://docs.sqlalchemy.org/en/14/orm/extensions/asyncio.html#using-asyncio-scoped-session
      async def start(self):
          self.async_session = AsyncSession()
  
      async def some_function(self, some_object):
          # use the AsyncSession directly
          self.async_session.add(some_object)
  
          # use the AsyncSession via the context-local proxy
          await AsyncSession.commit()
  
          # &quot;remove&quot; the current proxied AsyncSession for the local context
          await AsyncSession.remove()
  
  class Bar:
      async def start(self):
          self.async_session = AsyncSession()
  
      async def some_function(self, some_object):
          self.async_session.add(some_object)
          await self.async_session.commit()
  </code></pre>
  <p>I am using the method similar to in <code>Bar</code> elsewhere and kept getting the error</p>
  <pre><code>sqlalchemy.exc.PendingRollbackError: This Session's transaction has been rolled back due to a previous exception during flush. To begin a new transaction with this Session, first issue Session.rollback(). Original exception was: (sqlalchemy.dialects.postgresql.asyncpg.IntegrityError) &lt;class 'asyncpg.exceptions.UniqueViolationError'&gt;: duplicate key value violates unique constraint &quot;scores_pkey&quot;
  </code></pre>
  <p>When I try <code>Foo</code>, I get the error:</p>
  <pre><code>    await AsyncSession.remove()
  TypeError: object NoneType can't be used in 'await' expression
  </code></pre>