These special parameters allow functions to take arbitrary amounts of positional and keyword arguments. The names args
and kwargs
are purely convention, and could be named any other valid variable name. The special functionality comes from the single and double asterisks (*
). If both are used in a function signature, *args
must appear before **kwargs
.
Single asterisk
*args
will ingest an arbitrary amount of positional arguments, and store it in a tuple. If there are parameters after *args
in the parameter list with no default value, they will become required keyword arguments by default.
Python provides the ability to run multiple tasks and coroutines simultaneously with the use of the asyncio
library, which is included in the Python standard library.
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
Classes are used to create objects that have specific behavior.
Every object in Python has a class, including list
s, dict
Although most methods are tied to an object instance, it can sometimes be useful to create a method that does something with the class itself. To achieve this in Python, you can use the @classmethod
decorator. This is often used to provide alternative constructors for a class.
The assignment operator (=
) is used to assign variables.
x = 5
print(x) # Prints 5
The equality operator (Looking to contribute to Open Source Projects for the first time? Want to add a feature or fix a bug on the bots on this server? We have on-going projects that people can contribute to, even if you've never contributed to open source before!
Projects to Contribute to - Sir Lancebot - our fun, beginner-friendly bot - Python - our utility & moderation bot - Site - resources, guides, and more
Often you may find the need to use checks that don't exist by default in discord.py. Fortunately, discord.py provides discord.ext.commands.check
which allows you to create you own checks like this:
from discord.ext.commands import check, Context
def in_any_channel(*channels):
async def predicate(ctx: Context):
return ctx.channel.id in channels
return check(predicate)
This check is to check whether the invoked command is in a given set of channels. The inner function, named Cooldowns can be used in discord.py to rate-limit. In this example, we're using it in an on_message.
To learn more about how to create custom help commands in discord.py by subclassing the help command, please see this tutorial by Stella#2000
When trying to install a package via pip
, it's recommended to invoke pip as a module: python -m pip install your_package
.
Why would we use python -m pip
instead of pip
?
Invoking pip as a module ensures you know which pip you're using. This is helpful if you have multiple Python versions. You always know which Python version you're installing packages to.
A decorator is a function that modifies another function.
Consider the following example of a timer decorator:
The Python defaultdict
type behaves almost exactly like a regular Python dictionary, but if you try to access or modify a missing key, the defaultdict
will automatically insert the key and generate a default value for it.
While instantiating a defaultdict
, we pass in a function that tells it how to create a default value for missing keys.
>>> from collections import defaultdict
>>> my_dict = defaultdict(int)
>>> my_dict
defaultdict(<class 'int'>, {})
Often while using dictionaries in Python, you may run into KeyErrors
. This error is raised when you try to access a key that isn't present in your dictionary. Python gives you some neat ways to handle them.
The dict.get
Dictionary comprehensions (dict comps) provide a convenient way to make dictionaries, just like list comps:
>>> {word.lower(): len(word) for word in ('I', 'love', 'Python')}
{'i': 1, 'love': 4, 'python': 6}
The syntax is very similar to list comps except that you surround it with curly braces and have two expressions: one for the key and one for the value.Using free hosting options like repl.it for continuous 24/7 bot hosting is strongly discouraged. Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.
See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.
A docstring
is a string - always using triple quotes - that's placed at the top of files, classes and functions. A docstring should contain a clear explanation of what it's describing. You can also include descriptions of the subject's parameter(s) and what it returns, as shown below:
.env
(dotenv) files are a type of file commonly used for storing application secrets and variables, for example API tokens and URLs, although they may also be used for storing other configurable values. While they are commonly used for storing secrets, at a high level their purpose is to load environment variables into a program.
Dotenv files are especially suited for storing secrets as they are a key-value store in a file, which can be easily loaded in most programming languages and ignored by version control systems like Git with a single entry in a .gitignore
file.
Double-underscore methods, or "dunder" methods, are special methods defined in a class that are invoked implicitly. Like the name suggests, they are prefixed and suffixed with dunders. You've probably already seen some, such as the __init__
dunder method, also known as the "constructor" of a class, which is implicitly invoked when you instantiate an instance of a class.
When using JSON, you might run into the following error:
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
This error could have appeared because you just created the JSON file and there is nothing in it at the moment.Ever find yourself in need of the current iteration number of your for
loop? You should use enumerate! Using enumerate
, you can turn code that looks like this:
index = 0
for item in my_list:
print(f"{index}: {item}")
index += 1
into beautiful, The main purpose of Python virtual environments is to create an isolated environment for Python projects. This means that each project can have its own dependencies, such as third party packages installed using pip, regardless of what dependencies every other project has.
It's tempting to think that if statements always need a comparison operator like ==
or !=
, but this isn't true.
If you're just checking if a value is truthy or falsey, you don't need == True
or == False
.
A key part of the Python philosophy is to ask for forgiveness, not permission. This means that it's okay to write code that may produce an error, as long as you specify how that error should be handled. Code written this way is readable and resilient.
try:
number = int(user_input)
except ValueError:
print("failed to convert user_input to a number. setting number to 0.")
number = 0
You should always specify the exception type if it is possible to do so, and your If you want to exit your code programmatically, you might think to use the functions exit()
or quit()
, however this is bad practice. These functions are constants added by the site
module as a convenient method for exiting the interactive interpreter shell, and should not be used in programs.
You should use either SystemExit
or sys.exit()
instead.
There's not much practical difference between these two other than having to import sys
for the latter. Both take an optional argument to provide an exit status.
Creating a Python string with your variables using the +
operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f
in front of the first quote, you can then put Python expressions between curly braces in the string.
As the largest Python community on Discord, we get hundreds of questions every day. Many of these questions have been asked before. We've compiled a list of the most frequently asked questions along with their answers, which can be found on our FAQ page.
You may have noticed that when doing arithmetic with floats in Python you sometimes get strange results, like this:
>>> 0.1 + 0.2
0.30000000000000004
A specific word or set of words identified as a placeholder used in programming. They are used to name entities such as variables, functions, etc, whose exact identity is unimportant and serve only to demonstrate a concept, which is useful for teaching programming.
Common examples include foobar
, foo
, bar
, baz
, and qux
.
Python has its own metasyntactic variables, namely spam
, eggs
, and bacon
. This is a reference to a Monty Python sketch (the eponym of the language).
In Python it's possible to attach an else
clause to a for loop. The code under the else
block will be run when the iterable is exhausted (there are no more items to iterate over). Code within the else block will not run if the loop is broken out using break
.
Here's an example of its usage:
When assigning a new name to a function, storing it in a container, or passing it as an argument, a common mistake made is to call the function. Instead of getting the actual function, you'll get its return value.
When adding functions or classes to a program, it can be tempting to reference inaccessible variables by declaring them as global. Doing this can result in code that is harder to read, debug and test. Instead of using globals, pass variables or objects as parameters and receive return values.
The communities page on our website contains a number of communities we have partnered with as well as a curated list of other communities relating to programming and technology.
Should I be using is
or ==
?
To check if two objects are equal, use the equality operator (==
).
This is a statement that is only true if the module (your source code) it appears in is being run directly, as opposed to being imported into another module. When you run your module, the __name__
special variable is automatically set to the string '__main__'
. Conversely, when you import that same module into a different one, and run that, __name__
is instead set to the filename of your module minus the .py
extension.
In programming, there are two types of operations: - "In-place" operations, which modify the original object - "Out-of-place" operations, which returns a new object and leaves the original object unchanged
For example, the .sort()
method of lists is in-place, so it modifies the list you call .sort()
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Inline codeblocks look like this
. To create them you surround text with single backticks, so `hello` would become hello
.
Note that backticks are not quotes, see this if you are struggling to find the backtick key.
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are two common ways to iterate over a dictionary in Python. To iterate over the keys:
for key in my_dict:
print(key)
To iterate over both the keys and values:
The Kindling projects page on Ned Batchelder's website contains a list of projects and ideas programmers can tackle to build their skills and knowledge.
Do you ever find yourself writing something like this?
>>> squares = []
>>> for n in range(5):
... squares.append(n ** 2)
[0, 1, 4, 9, 16]
Using list comprehensions can make this both shorter and more readable. As a list comprehension, the same code would look like this:
Thanks to discord.py, sending local files as embed images is simple. You have to create an instance of discord.File
class:
Avoid adding to or removing from a collection, such as a list, as you iterate that collection in a for
loop:
data = [1, 2, 3, 4]
for item in data:
data.remove(item)
print(data) # [2, 4] <-- every OTHER item was removed!
Inside the loop, an index tracks the current position. If the list is modified, this index may no longer refer to the same element, causing elements to be repeated or skipped.The Discord gateway only dispatches events you subscribe to, which you can configure by using "intents."
The message content intent is what determines if an app will receive the actual content of newly created messages. Without this intent, discord.py won't be able to detect prefix commands, so prefix commands won't respond.
When you install a library through pip
on Windows, sometimes you may encounter this error:
error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
<@!683001325440860340> is a bot that will relay your messages to our moderation team, so that you can start a conversation with the moderation team. Your messages will be relayed to the entire moderator team, who will be able to respond to you via the bot.
It supports attachments, codeblocks, and reactions. As communication happens over direct messages, the conversation will stay between you and the mod team.
Imagine that you want to make all letters in a string upper case. Conveniently, strings have an .upper()
method.
You might think that this would work:
Default arguments in Python are evaluated once when the function is defined, not each time the function is called. This means that if you have a mutable default argument and mutate it, you will have mutated that object for all future calls to the function as well.
For example, the following
A name is a piece of text that is bound to an object. They are a reference to an object. Examples are function names, class names, module names, variables, etc.
Note: Names cannot reference other names, and assignment never creates a copy.
If you've installed a package but you're getting a ModuleNotFoundError when you try to import it, it's likely that the environment where your code is running is different from the one where you did the installation.
You can read about Python environments at /tag environments
and /tag venv
.
There are three off-topic channels: - <#291284109232308226> - <#463035241142026251> - <#463035268514185226>
The channel names change every night at midnight UTC and are often fun meta references to jokes or conversations that happened on the server.
Registering the on_message
event with @bot.event
will override the default behavior of the event. This may cause prefix commands to stop working, because they rely on the default on_message
event handler.
Instead, use @bot.listen
to add a listener. Listeners get added alongside the default
The built-in function open()
is one of several ways to open files on your computer. It accepts many different parameters, so this tag will only go over two of them (file
and mode
). For more extensive documentation on all these parameters, consult the official documentation. The object returned from this function is a file object or stream, for which the full documentation can be found here.
See also:
- !tags with
for information on context managers
- !tags pathlib
for an alternative way of opening files
- !tags seek
for information on changing your position in a file
When checking if something is equal to one thing or another, you might think that this is possible:
# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have A parameter is a variable defined in a function signature (the line with def
in it), while arguments are objects passed to a function call.
def square(n): # n is the parameter
return n*n
print(square(5)) # 5 is the argument
If your code is too long to fit in a codeblock in Discord, you can paste your code here: https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S
Python 3 comes with a new module named Pathlib
. Since Python 3.6, pathlib.Path
objects work nearly everywhere that os.path
can be used, meaning you can integrate your new code directly into legacy code without having to rewrite anything. Pathlib makes working with paths way simpler than os.path
does.
Feature spotlight:
PEP 8 is the official style guide for Python. It includes comprehensive guidelines for code formatting, variable naming, and making your code easy to read. Professional Python developers are usually required to follow the guidelines, and will often use code-linters like flake8 to verify that the code they're writing complies with the style guide.
Functions can take two different kinds of arguments. A positional argument is just the object itself. A keyword argument is a name assigned to an object.
Example
Operator precedence is essentially like an order of operations for Python's operators.
Example 1 (arithmetic)
2 * 3 + 1
is 7
because multiplication is first
2 * (3 + 1)
is 8
because the parenthesis change the precedence allowing the sum to be first
Single and Double quoted strings are the same in Python. The choice of which one to use is up to you, just make sure that you stick to that choice.
With that said, there are exceptions to this that are more important than consistency. If a single or double quote is needed inside the string, using the opposite quotation is better than using escape characters.
Beginners often iterate over range(len(...))
because they look like Java or C-style loops, but this is almost always a bad practice in Python.
for i in range(len(my_list)):
do_something(my_list[i])
It's much simpler to iterate over the list (or other sequence) directly:
Regular expressions (regex) are a tool for finding patterns in strings. The standard library's re
module defines functions for using regex patterns.
Example We can use regex to pull out all the numbers in a sentence:
A relative path is a partial path that is relative to your current working directory. A common misconception is that your current working directory is the location of the module you're executing, but this is not the case. Your current working directory is actually the directory you were in when you ran the Python interpreter. The reason for this misconception is because a common way to run your code is to navigate to the directory your module is stored, and run python <module>.py
. Thus, in this case your current working directory will be the same as the location of the module. However, if we instead did python path/to/<module>.py
, our current working directory would no longer be the same as the location of the module we're executing.
Why is this important?
A REPL is an interactive shell where you can execute individual lines of code one at a time, like so:
>>> x = 5
>>> x + 2
7
>>> for i in range(3):
... print(i)
...
0
1
2
>>>
To enter the REPL, run A value created inside a function can't be used outside of it unless you return
it.
Consider the following function:
Here's a handy animation demonstrating how print
and return
differ in behavior.
See also: /tag return
Python 3 uses bankers' rounding (also known by other names), where if the fractional part of a number is .5
, it's rounded to the nearest even result instead of away from zero.
Example:
A scope defines the visibility of a name within a block, where a block is a piece of Python code executed as a unit. For simplicity, this would be a module, a function body, and a class definition. A name refers to text bound to an object.
For more information about names, see /tag names
In the context of a file object, the seek
function changes the stream position to a given byte offset, with an optional argument of where to offset from. While you can find the official documentation here, it can be unclear how to actually use this feature, so keep reading to see examples on how to use it.
When calling a method from a class instance (ie. instance.method()
), the instance itself will automatically be passed as the first argument implicitly. By convention, we call this self
, but it could technically be called any valid variable name.
class Foo:
def bar(self):
print('bar')
def spam(self, eggs):
print(eggs)
foo = Foo()
Our official website is an open-source community project created with Python and Django. It contains information about the server itself, lets you sign up for upcoming events, has its own wiki, contains a list of valuable learning resources, and much more.
Slicing is a way of accessing a part of a sequence by specifying a start, stop, and step. As with normal indexing, negative numbers can be used to count backwards.
Examples
Don't use f-strings (f""
) or other forms of "string interpolation" (%
, +
, .format
) to inject data into a SQL query. It is an endless source of bugs and syntax errors. Additionally, in user-facing applications, it presents a major security risk via SQL injection.
Your database library should support "query parameters". A query parameter is a placeholder that you put in the SQL query. When the query is executed, you provide data to the database library, and the library inserts the data into the query for you, safely.
Wildcard imports are import statements in the form from <module_name> import *
. What imports like these do is that they import everything [1] from the module into the current module's namespace [2]. This allows you to use names defined in the imported module without prefixing the module's name.
If you want to display a list (or some other iterable), you can write:
colors = ['red', 'green', 'blue', 'yellow']
output = ""
separator = ", "
for color in colors:
output += color + separator
print(output)
# Prints 'red, green, blue, yellow, '
However, the separator is still added to the last element, and it is relatively slow.The String Formatting Language in Python is a powerful way to tailor the display of strings and other data structures. This string formatting mini language works for f-strings and .format()
.
Take a look at some of these examples!
When working with strip
, lstrip
, or rstrip
, you might think that this would be the case:
>>> "Monty Python".rstrip(" Python")
"Monty"
While this seems intuitive, it would actually result in:
Why Avoid System Python for Development on Unix-like Systems:
- Critical Operating System Dependencies: Altering the system Python installation may harm internal operating system dependencies.
The Tools page on our website contains a couple of the most popular tools for programming in Python.
Please provide the full traceback for your exception in order to help us identify your issue. While the last line of the error message tells us what kind of error you got, the full traceback will tell us which line, and other critical information to solve your problem. Please avoid screenshots so we can copy and paste parts of the message.
A type hint indicates what type a variable is expected to be.
def add(a: int, b: int) -> int:
return a + b
The type hints indicate that for our __name__
: Used to implement special behaviour, such as the+
operator for classes with the__add__
method. More info_name
: Indicates that a variable is "private" and should only be used by the class or module that defines itname_
: Used to avoid naming conflicts. For example, asclass
is a keyword, you could call a variableclass_
instead__name
: Causes the name to be "mangled" if defined inside a class. More info
Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.
To create a new virtual environment, you can use the standard library venv
module: python3 -m venv .venv
(replace python3
with python
or py
on Windows)
Can’t talk in voice chat? Check out <#764802555427029012> to get access. The criteria for verifying are specified there.
If you have installed Python but forgot to check the Add Python to PATH
option during the installation, you may still be able to access your installation with ease.
If you did not uncheck the option to install the py launcher
, then you'll instead have a py
The with
keyword triggers a context manager. Context managers automatically set up and take down data connections, or any other kind of object that implements the magic methods __enter__
and __exit__
.
with open("test.txt", "r") as file:
do_things(file)
The above code automatically closes The XY problem can be summarised as asking about your attempted solution, rather than your actual problem.
Often programmers will get distracted with a potential solution they've come up with, and will try asking for help getting it to work. However, it's possible this solution either wouldn't work as they expect, or there's a much better solution instead.
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The zip function allows you to iterate through multiple iterables simultaneously. It joins the iterables together, almost like a zipper, so that each new element is a tuple with one element from each iterable.