This article discusses the error ‘RuntimeWarning: Enable tracemalloc to get the object allocation traceback‘ in Python. If you are facing the same problem, check out the information below to find out the cause of this error and how to fix it by using the keyword ‘await‘.
The cause of this error
First, we need to know that ‘asyncio‘ is a library for writing concurrent code using the async/await syntax. The sleep() method of this module is used to delay the currently executing task and allow another task to be executed.
Syntax:
asyncio.sleep(delay, result=None)
The reason why we received the error is that we forgot to use the “await” keyword before the sleep() method.
To illustrate, let me reproduce the error:
import asyncio
async def main():
print('Loading…')
asyncio.sleep(3)
print('Welcome to our site. We are LearnShareIT!')
asyncio.run(main())
Output:
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
To fix this problem, you just need to add the keyword ‘await‘ before calling the sleep() method.
The ‘await‘ keyword is used as the signal to mark the breakpoint. It allows a coroutine to temporarily suspend execution and allow the program to return to it later.
Continuing with the example above, let’s see how we fix this problem:
import asyncio
async def main():
print('Loading…')
# Add the 'await' keyword in front of the asyncio.sleep() method
await asyncio.sleep(3)
print('Welcome to our site. We are LearnShareIT!')
asyncio.run(main())
Output:

At this point the error seems to have been solved with just a small change in the code.
We set the block time to three seconds in the sleep() method. As you can see, the message ‘Loading…‘ appears first, then after ‘3‘ seconds message ‘Welcome to our site. We are LearnShareIT!‘ is printed.
Summary
To sum up, that’s all we want to talk about the error ‘RuntimeWarning: Enable tracemalloc to get the object allocation traceback‘ in Python. To solve this problem, you have to use the ‘await‘ keyword before calling the asyncio.sleep() method. Try it out in your project and see the results. Hopefully, the information we provide in this post will be helpful to you.
Maybe you are interested:
- RuntimeError: dictionary changed size during iteration
- Statements must be separated by newlines or semicolons

My name’s Christopher Gonzalez. I graduated from HUST two years ago, and my major is IT. So I’m here to assist you in learning programming languages. If you have any questions about Python, JavaScript, TypeScript, Node.js, React.js, let’s contact me. I will back you up.
Name of the university: HUST
Major: IT
Programming Languages: Python, JavaScript, TypeScript, Node.js, React.js
Trying to use a semaphore to control asynchronous requests to control the requests to my target host but I am getting the following error which I have assume means that my asycio.sleep() is not actually sleeping. How can I fix this? I want to add a delay to my requests for each URL targeted.
Error:
RuntimeWarning: coroutine 'sleep' was never awaited
Coroutine created at (most recent call last)
File "sephora_scraper.py", line 71, in <module>
loop.run_until_complete(main())
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/base_events.py", line 571, in run_until_complete
self.run_forever()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/base_events.py", line 539, in run_forever
self._run_once()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/base_events.py", line 1767, in _run_once
handle._run()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/events.py", line 88, in _run
self._context.run(self._callback, *self._args)
File "makeup.py", line 26, in get_html
asyncio.sleep(delay)
asyncio.sleep(delay)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Code:
import sys
import time
import asyncio
import aiohttp
async def get_html(semaphore, session, url, delay=6):
await semaphore.acquire()
async with session.get(url) as res:
html = await res.text()
asyncio.sleep(delay)
semaphore.release()
return html
async def main():
categories = {
"makeup": "https://www.sephora.com/shop/"
}
semaphore = asyncio.Semaphore(value=1)
tasks = []
async with aiohttp.ClientSession(loop=loop, connector=aiohttp.TCPConnector(ssl=False)) as session:
for category, url in categories.items():
# Get HTML of all pages
tasks.append(get_html(semaphore, session, url))
res = await asyncio.gather(*tasks)
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Hello Guys, How are you all? Hope You all Are Fine. Today I am just trying to use asycio.sleep() in my code but I am facing following error in Python. So Here I am Explain to you all the possible solutions here.
Without wasting your time, Let’s start This Article to Solve This Error.
Contents
- How RuntimeWarning: Enable tracemalloc to get the object allocation traceback Error Occurs ?
- How To Solve RuntimeWarning: Enable tracemalloc to get the object allocation traceback Error ?
- Solution 1: asyncio.sleep should be awaited
- Summary
I am just trying to use asycio.sleep() in my code but I am facing following error.
RuntimeWarning: coroutine ‘sleep’ was never awaited
asyncio.sleep(delay)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
How To Solve RuntimeWarning: Enable tracemalloc to get the object allocation traceback Error ?
- How To Solve RuntimeWarning: Enable tracemalloc to get the object allocation traceback Error ?
To Solve RuntimeWarning: Enable tracemalloc to get the object allocation traceback Error Here asyncio.sleep is a coroutine and that’s why that should be awaited. Just like This: await asyncio.sleep(delay) Now your error should be solved.
- RuntimeWarning: Enable tracemalloc to get the object allocation traceback
To Solve RuntimeWarning: Enable tracemalloc to get the object allocation traceback Error Here asyncio.sleep is a coroutine and that’s why that should be awaited. Just like This: await asyncio.sleep(delay) Now your error should be solved.
Solution 1: asyncio.sleep should be awaited
Here asyncio.sleep is a coroutine and that’s why that should be awaited. Just like This.
await asyncio.sleep(delay)
Now your error should be solved.
Summary
It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you?
Also, Read
- Found conflicts! Looking for incompatible packages. This can take several minutes. Press CTRL-C to abort
Are you having problems with the issue “RuntimeWarning: Enable tracemalloc to get the object allocation traceback“? How to fix it? In today’s article, I will provide solutions for you to solve the issues. Please follow the below steps to get the problem resolved now
How did “RuntimeWarning: Enable tracemalloc to get the object allocation traceback” occur?
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
When you work with Python, you may get the issue RuntimeWarning: Enable tracemalloc to get the object allocation traceback. Don’t worry, we are here to provide you solutions in order to resolve your problem.
How to fix “RuntimeWarning: Enable tracemalloc to get the object allocation traceback”?
To Solve RuntimeWarning, enable tracemalloc to obtain the object allocation traceback error. asyncio.sleep is a coroutine. It should be awaited. Now, just pke This.
Solution 1: asyncio.sleep is the best solution
This asyncio.sleep is a coroutine. It’s worth waiting for. As simple as this.
await asyncio.sleep(delay)
Your error should now be fixed
Final words
The above are useful solutions that can help you fix “RuntimeWarning: Enable tracemalloc to get the object allocation traceback” problem, if you can’t solve it well. Please leave a message.
When I call a coroutine without awaiting, in addition to a message warning me I have not awaited the coroutine, I also get the following warning message:
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
I know how to fix this i.e. by awaiting the coroutine (and I do see a lot of questions about this warning, but all the answers are how to fix it; my goal is to understand it; please don’t mark my question as duplicate if possible 🙂 ); in particular, what I’d really like to understand is:
- What is tracemalloc? How do I enable it?
- What is the object allocation traceback?
- How is it related to coroutines? and, in particular
- Why is there a warning suggesting to enable tracemalloc when I don’t await a coroutine?
My goal in asking this is understanding the details and inner-workings of asyncio better.
asked Aug 22, 2022 at 11:13
- What is tracemalloc? How do I enable it?
tracemalloc is a module that is used to debug memory allocation in python
you can enable it by setting PYTHONTRACEMALLOC environment variable to 1
check the docs for more info Tracemalloc docs
- What is the object allocation traceback
It’s a way how python manages memory and allocates memory for it’s objects
- Why is there a warning suggesting to enable tracemalloc when I don’t await a coroutine?
I guess this is because memory is allocated and never used properly so we get loss of resources i.e memory leak
answered Aug 22, 2022 at 16:41
1
When I call a coroutine without awaiting, in addition to a message warning me I have not awaited the coroutine, I also get the following warning message:
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
I know how to fix this i.e. by awaiting the coroutine (and I do see a lot of questions about this warning, but all the answers are how to fix it; my goal is to understand it; please don’t mark my question as duplicate if possible 🙂 ); in particular, what I’d really like to understand is:
- What is tracemalloc? How do I enable it?
- What is the object allocation traceback?
- How is it related to coroutines? and, in particular
- Why is there a warning suggesting to enable tracemalloc when I don’t await a coroutine?
My goal in asking this is understanding the details and inner-workings of asyncio better.
asked Aug 22, 2022 at 11:13
- What is tracemalloc? How do I enable it?
tracemalloc is a module that is used to debug memory allocation in python
you can enable it by setting PYTHONTRACEMALLOC environment variable to 1
check the docs for more info Tracemalloc docs
- What is the object allocation traceback
It’s a way how python manages memory and allocates memory for it’s objects
- Why is there a warning suggesting to enable tracemalloc when I don’t await a coroutine?
I guess this is because memory is allocated and never used properly so we get loss of resources i.e memory leak
answered Aug 22, 2022 at 16:41
1
Ok. Warning, my main.py is still long.
import discord as d from discord_webhook import DiscordWebhook import sys, traceback from discord.ext.commands import Bot from discord.ext.commands import bot_has_permissions from discord.ext.commands import has_permissions from discord.ext import commands as c import os from random import randint import sqlite3 as sql import asyncio from keep_alive import keep_alive conn = sql.connect('Ratchet.db') crsr = conn.cursor() class MyClient(Bot): def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) async def on_ready(self): for cog in cogs: self.load_extension(cog) """try: crsr.execute('DROP TABLE guilds;') conn.commit except sql.OperationalError: pass try: crsr.execute('DROP TABLE users;') conn.commit except sql.OperationalError: pass crsr.execute('CREATE TABLE guilds ( guild_id UNSIGNED BIG integer NOT NULL, prefix string );') conn.commit for guild in self.guilds: crsr.execute('INSERT INTO guilds (guild_id, prefix) VALUES (?, ?)', (guild.id, '\')) conn.commit crsr.execute('UPDATE guilds SET prefix=? WHERE guild_id=?',('&',550722337050198036)) crsr.execute('CREATE TABLE users ( guild_id UNSIGNED BIG INT, user_id UNSIGNED BIG INT, xp INT );') conn.commit()""" print('Logged in as') print('{0.user}'.format(self)) print('Serving', end=' ') print('{} server(s)'.format(len(self.guilds))) while not self.is_closed(): await self.change_presence(activity=d.Activity(type=d.ActivityType.watching, name='\help')) await asyncio.sleep(5) await self.change_presence(activity=d.Activity(type=d.ActivityType.watching, name=f'{len(self.guilds)} servers')) await asyncio.sleep(5) async def on_message(self,message): if not message.author.bot: try: crsr.execute('SELECT xp FROM users WHERE guild_id=? AND user_id=?', (message.guild.id, message.author.id)) idk = crsr.fetchone() #await message.channel.send(idk) if idk is None: #user not ranked crsr.execute('INSERT INTO users (guild_id, user_id, xp) VALUES (?, ?, ?)', (message.guild.id, message.author.id, 1)) else: crsr.execute('UPDATE users SET xp=? WHERE guild_id=? AND user_id=?', ((idk[0] or 0) + 1, message.guild.id, message.author.id)) conn.commit() except AttributeError: pass await self.process_commands(message) def get_prefix(bot,msg): try: crsr.execute('SELECT prefix FROM guilds WHERE guild_id=?',(msg.guild.id,)) idk = crsr.fetchone() if idk is None or idk[0] is None: return '\' return (idk[0], '\') crsr.commit() except AttributeError: return ['&','\'] client = MyClient(command_prefix=get_prefix) client.crsr = crsr client.conn = conn cogs = ['Bot','Moderation','Miscellaneous','Games','errorhandler','owner'] with open('Ratchet/login.txt') as f: token = f.readline().strip() keep_alive() try: client.loop.run_until_complete(client.start(token)) except KeyboardInterrupt: conn.close() client.loop.run_until_complete(client.logout()) finally: client.loop.close() conn.close()