Lesson 36 of 55
8 mins readPython Metatable Protection (__metatable)
In Plain English
Setting the `__metatable` field in a metatable prevents callers from modifying it with `setmetatable` and hides its true contents from `getmetatable`.
Deep Dive: How It Works
Protected Metatable: `meta.__metatable = "Protected"` locks the metatable.
getmetatable(t): Returns the string in `meta.__metatable` instead of the actual table.
setmetatable(t, new_meta): Throws a runtime error `cannot change a protected metatable`.
Core Rules to Remember

Locking Metatables: Guarantees integrity of object prototypes and library APIs.

Security & Encapsulation: Prevents external code from tampering with object metamethods.
Live Interactive Example
Hit Run Code to see it liveLocking a Metatable
Python 3.12
1
2
3
4
5
6
7
8
9
10
Output Console
Click "Run Code" to view the rendered output.
How it works: getmetatable returned the lock string instead of the raw metatable.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Protect Metatable with Message
Create `local mt = { __metatable = "Locked" }` and set on `local obj = {}`.
Print `"Status: " .. getmetatable(obj)`.
1
2
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.