0
0
Pythonprogramming~5 mins

Built-in scope in Python

Choose your learning style9 modes available
Introduction

Built-in scope holds names of functions and variables that Python always knows. It helps you use common tools without extra work.

When you use functions like <code>print()</code> or <code>len()</code> without defining them yourself.
When you want to understand why a name works even if you didn't create it.
When debugging to see if a name is from your code or Python's built-ins.
When you want to avoid naming your variables the same as built-in names to prevent confusion.
Syntax
Python
No special syntax to access built-in scope directly.
Python automatically looks here if a name is not found in local or global scopes.

Built-in scope is the last place Python looks for a name.

You can see built-in names using the dir(__builtins__) command.

Examples
Uses built-in functions print() and len() without defining them.
Python
print(len("hello"))
max() is a built-in function that finds the largest number in a list.
Python
x = max([1, 5, 3])
print(x)
Shows that print is part of the built-in scope.
Python
import builtins
print('print' in dir(builtins))
Sample Program

This program shows the built-in len() function and a user-made version. It also checks if len is in the built-in scope.

Python
def my_len(s):
    count = 0
    for _ in s:
        count += 1
    return count

print(len('hello'))  # built-in len
print(my_len('hello'))  # user-defined len

import builtins
print('len' in dir(builtins))  # check if len is built-in
OutputSuccess
Important Notes

Built-in names include functions like print, len, max, and constants like True, None.

Avoid naming your variables the same as built-in names to prevent bugs.

You can override built-in names, but it is not recommended because it can cause confusion.

Summary

Built-in scope contains names Python always knows.

Python looks here last when finding a name.

Use built-in functions freely, but avoid naming conflicts.