Zum Hauptinhalt springen
LIVE
CVSS 7.0CVE-2026-138158 | libgphoto2 through 2.5.34 contains a stack buffer overflow in sierra_get_string_register() that lets a malicious sierra-protocol camera or USB device overwrite stack memory. When files are listed, the device can answer the file-name register with an oversized packet, writing up to 32 KB past small stack buffers to cause crashes or possible code execution.CVSS 7.7CVE-2026-138159 | edbrowse through 3.8.19 contains an integer overflow in stringAndBytes() that allows malicious servers to write past a heap buffer by sending response bodies larger than 2 GB. When a user browses to an attacker-controlled HTTP, FTP, or gopher server, the oversized body skips reallocation and corrupts the heap, causing crashes or potentially code execution.CVSS 8.5CVE-2026-138160 | Gammu before 1.45.2 contains a stack-based buffer overflow vulnerability in ReadBackupTextLen() that allows attackers to overwrite stack memory via crafted backup files. Attackers can supply overlong quoted text values decoded into a 10,000-byte stack array during convertbackup, restore, or GSM_ReadBackupFile calls, causing crashes or potential code execution.CVSS 8.5CVE-2026-138161 | Gammu before 1.45.2 contains a buffer overflow vulnerability in LoadBackup() that allows attackers to corrupt memory by supplying an overlong MD5 value in a crafted backup file. Attackers can overwrite adjacent phonebook and calendar entry pointers via strcpy() into MD5Original when files are loaded with convertbackup or restore, causing crashes or potential code execution.CVSS 7.3CVE-2026-138162 | Gammu before 1.45.2 contains a stack-based buffer overflow vulnerability in ALCATEL_EncodeString() that allows attackers to overwrite stack memory via oversized encoded phonebook text. Attackers can supply a crafted backup restored with gammu restore or addnew to an attached Alcatel phone, using GSM extension characters to crash Gammu or potentially execute code.CVSS 8.5CVE-2026-138163 | Gammu before 1.45.2 contains a heap-based buffer overflow in ReadWAPSettingsEntry() that allows attackers to corrupt heap memory via crafted backup files with excess WAP or MMS settings entries. Attackers can supply a backup with more than four TitleNN keys in a [WAPSettings] or [MMSSettings] section, loaded via convertbackup, restore, or GSM_ReadBackupFile, causing crashes or potential code execution.CVSS 4.8CVE-2026-138164 | Gammu before 1.45.2 contains a stack-based buffer overflow vulnerability in SaveBackupText() in backtext.c that allows attackers to corrupt stack memory by supplying long text fields. Attackers can craft a backup with long calendar or note fields that, when converted with gammu convertbackup, writes hex digits past the 10,000-byte stack buffer.CVSS 9.3CVE-2026-138154 | POSTAL 2 before build 26810491 contains a sandbox escape vulnerability that allows malicious Steam Workshop mods to execute code by calling ConsoleCommand with a start file URI. Attackers can ship a batch file in a mod at the predictable workshop install path and launch it via ShellExecuteW, executing commands as the player on Windows.
Alle im Drawer
Intelligence View
⚡ tsecurity.de Intelligence

Closures in Python Explained by Tracing Through the Code

Closures in Python Explained by Tracing Through the Code Most explanations of closures start with a definition. This one starts with code. Understanding what a…

Beitrag
0
Seite
0
↗ Quelle (dev.to)
Quelle & Fakten · 4 Min. Lesezeit
Quelle: dev.to
Rubrik: Sichere Programmierung




Closures in Python Explained by Tracing Through the Code



Most explanations of closures start with a definition. This one starts with code. Understanding what a closure actually is by watching one form step by step.



Read this and tell me what it prints:




def outer():
x = 10
def inner():
print(x)
return inner

func = outer()
func()







If you said 10, you are right. But the more interesting question is why it prints 10 when outer has already finished executing and its local scope should be completely gone.



That question is the entire point of closures.









What a Closure Actually Is



When outer returns the inner function, Python notices that inner references a variable from the enclosing scope (x). Rather than letting that variable disappear when outer's stack frame is destroyed, Python keeps it alive by attaching it directly to the inner function object.



This combination, a function plus the variables it has captured from an enclosing scope, is called a closure.



You can see the captured variables directly by inspecting the function:




func = outer()
print(func.__closure__)
# Output: (<cell object at 0x...>,)

print(func.__closure__[0].cell_contents)
# Output: 10







The variable x lives inside a cell object attached to the function. It persists as long as the function object exists, regardless of what happened to the original scope where it was defined.









Tracing a Closure Step by Step






def make_counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment

counter = make_counter()
print(counter())
print(counter())
print(counter())







Let us trace each execution step:




































Call count before operation count after returns
counter() 0 count += 1 1 1
counter() 1 count += 1 2 2
counter() 2 count += 1 3 3


Output:




1
2
3







The variable count persists between calls because it lives in the closure cell, not in a fresh local scope. Each call to counter accesses and modifies the exact same underlying count object.









The Late Binding Trap



This is the closure behavior that catches the most developers off guard during technical screens.




functions = []
for i in range(5):
def func():
return i
functions.append(func)

print([f() for f in functions])







Most people expect [0, 1, 2, 3, 4].



Actual output: [4, 4, 4, 4, 4]



The reason: all five functions close over the same variable i in the enclosing scope, not over the value of i at the time each function was created. By the time the functions are called, the loop has finished and i is 4. All five functions look up i and find 4.



The fix is to capture the current value as a default argument:




functions = []
for i in range(5):
def func(i=i):
return i
functions.append(func)

print([f() for f in functions])
# Output: [0, 1, 2, 3, 4]







Default arguments are evaluated at function definition time, not at call time. This means each function captures the current value of i at that specific iteration as its own private default parameter.









Two Closures, One Shared State






def make_account(balance):
def deposit(amount):
nonlocal balance
balance += amount
return balance

def withdraw(amount):
nonlocal balance
balance -= amount
return balance

return deposit, withdraw

dep, with_ = make_account(100)
print(dep(50))
print(with_(30))
print(dep(20))







Both deposit and withdraw close over the same balance variable. Changes made through one function are completely visible to the other.



Output:




150
120
140







This pattern is a simple way to create stateful objects without using formal classes. It is also a pattern that appears in interviews specifically because the shared state behavior surprises people who think of closures as isolated instances.









Three Interview Problems on Closures






Problem 1






def multiplier(n):
def multiply(x):
return x * n
return multiply

double = multiplier(2)
triple = multiplier(3)

print(double(5))
print(triple(5))
print(double(triple(2)))







Output:




10
15
12







Each call to multiplier creates a new closure with its own independent n. double has n=2, and triple has n=3. The evaluation double(triple(2)) processes triple(2) first which gives 6, then double(6) which gives 12.






Problem 2






def outer(x):
def inner(y):
def innermost(z):
return x + y + z
return innermost
return inner

result = outer(1)(2)(3)
print(result)







Output: 6



Three nested closures each capturing one variable from their enclosing scope. The innermost function has immediate access to all three layers. 1 + 2 + 3 = 6.






Problem 3






adders = [lambda x, n=n: x + n for n in range(4)]
print([f(10) for f in adders])







Output: [10, 11, 12, 13]



The n=n pattern captures the current value of n at each iteration. Without it, you would get [13, 13, 13, 13] due to the late binding trap.









Practice Coding Exercises



Closures are one of the more frequently tested Python concepts in mid to senior level interviews because they reveal whether a candidate understands name lookup, scope boundaries, and object lifetime at a deeper level than surface syntax.



Practice tracing closure problems and predicting their exact terminal output at PyCodeIt. The platform serves up custom dry-run code logic to help you build true pattern recognition. Test your skills at pycodeit.com.






Written by the developer behind PyCodeIt, a free AI-powered Python dry-run practice platform for technical interview preparation.

Information ergänzen Fachhinweis, Update, Korrektur oder Quelle zur Meldung beitragen
Gäste-Hinweise werden kurz redaktionell geprüft und danach hier angezeigt.

Community-Hinweise zur Meldung

0 freigegeben
Social ReaktionenReagiere als Erste:r — dein Feedback zählt!
Informations-Bewertung:

💬 Communitydiscussie & reacties

🌐 Naar de hoofdchat

Start de discussie in de Social Chat broadcaststream of dien hierboven een vakbijdrage in via het aanvulformulier.

Cyber Threat Intelligence & Forensiek

ATT&CK-Navigator · IoC-Radar & Graaf

CTI Threat Relationship Graph
Akteure · Techniken · Beziehungen
2 Knoten · 1 Relationen
CVE / Incident Threat Actor Software MITRE ATT&CK CWE Weakness IoC
Community Rating &amp; Social Proof
⭐ Lezersbeoordeling
–
Ø / 5.0
Nog geen recensies van lezers
Was dit artikel nuttig?
0
Geef uw beoordeling
Detailbeoordeling (optioneel)
Inhoud & Kwaliteit
Bron & Geloofwaardigheid
Actualiteit
Security Briefing Gratis · 1-klik uitschrijven

Intelligence Digest gratis

Dagelijks het belangrijkste beveiligingsnieuws · kan op elk moment worden opgehaald

Verwant Story Cluster & Sources (vector AI)

6 Cluster
21 Bronnen
CVE-2026-72109 | Linux Kernel up to 7.1.4 sparx5 sparx5_register_notifier_blocks allocation of resources (WID-SEC-2026-2852)
VulDB Updates 2 uur geleden
20 andere bronnen
VulDB Updates2 uur geledenCVE-2026-72110 | Linux Kernel up to 7.2-rc1 BPF bpf_local_storage_destroy use after free (WID-SEC-2026-2852) VulDB Updates2 uur geledenCVE-2026-72112 | Linux Kernel up to 7.1.4/7.2-rc3 BPF Ops io_uring io_install_bpf priv/ring_fd use after free (WID-SEC-2026-2852) VulDB Updates2 uur geledenCVE-2026-72113 | Linux Kernel up to 7.2-rc3 bcm bcm.c bcm_release/bcm_delete_rx_op/bcm_notifier rx_reg_dev use after free (WID-SEC-2026-2852) VulDB Updates2 uur geledenCVE-2026-72114 | Linux Kernel up to 7.2-rc3 bcm bcm_rx_setup len buffer overflow (WID-SEC-2026-2852) VulDB Updates2 uur geledenCVE-2026-72115 | Linux Kernel up to 7.2-rc3 bcm bcm_rx_handler race condition (WID-SEC-2026-2852) VulDB Updates2 uur geledenCVE-2026-72116 | Linux Kernel up to 7.2-rc3 bcm bcm_rx_setup race condition (WID-SEC-2026-2852) VulDB Updates2 uur geledenCVE-2026-72117 | Linux Kernel up to 7.2-rc3 bcm bcm_rx_handler locking (WID-SEC-2026-2852) VulDB Updates2 uur geledenCVE-2026-72118 | Linux Kernel up to 7.2-rc3 bcm bcm_rx_handler race condition (WID-SEC-2026-2852) VulDB Updates2 uur geledenCVE-2026-72119 | Linux Kernel up to 7.2-rc3 bcm net/can/bcm.c bcm_tx_setup race condition (WID-SEC-2026-2852) DEV Community3 uur geledenKnuth's moratorium on error reports: what his page says, why repeats cost time, and what curl and the Linux kernel did VulDB Updates4 uur geledenCVE-2026-72099 | Linux Kernel up to 7.2-rc2 dm-integrity infinite loop (Nessus ID 364704 / WID-SEC-2026-2852) VulDB Updates4 uur geledenCVE-2026-72100 | Linux Kernel up to 6.12.96/6.18.39/7.1.4/7.2-rc2 dm-integrity deadlock (WID-SEC-2026-2852) VulDB Updates4 uur geledenCVE-2026-72101 | Linux Kernel up to 6.12.100/6.18.39/7.1.4/7.2-rc2 dm-integrity uninitialized pointer (WID-SEC-2026-2852) VulDB Updates4 uur geledenCVE-2026-72103 | Linux Kernel up to 6.12.100/6.18.41/7.1.4/7.2-rc2 dm-crypt crypt_set_keyring_key information disclosure (WID-SEC-2026-2852) VulDB Updates4 uur geledenCVE-2026-72102 | Linux Kernel up to 7.2-rc2 Device Mapper dm_early_create use after free (WID-SEC-2026-2852) VulDB Updates4 uur geledenCVE-2026-72104 | Linux Kernel up to 6.18.39/7.1.4/7.2-rc2 dm-pcache parse_cache_opts null pointer dereference (WID-SEC-2026-2852) VulDB Updates4 uur geledenCVE-2026-72105 | Linux Kernel up to 7.2-rc2 dm-log out-of-bounds write (WID-SEC-2026-2852) VulDB Updates4 uur geledenCVE-2026-72107 | Linux Kernel up to 7.2-rc2 dm era writeset_marked out-of-bounds (WID-SEC-2026-2852) VulDB Updates4 uur geledenCVE-2026-72106 | Linux Kernel up to 7.2-rc2 dm-ioctl list_version_get_info buffer overflow (Nessus ID 335743 / WID-SEC-2026-2852) VulDB Updates4 uur geledenCVE-2026-72108 | Linux Kernel up to 7.2-rc2 dm thin metadata __reserve_metadata_snap/__release_metadata_snap reference count (WID-SEC-2026-2852)
19 Bronnen
'King-sized' Black Friday deal: Save 79% off Paramount+
Latest from TechRadar 1 uur geleden
18 andere bronnen
Latest from TechRadar58 min. geledenBig features, tiny price tags: The 4 best-value VPN deals of Black Friday 2026 Latest from Windows Central1 uur geledenThe best Xbox and PC Black Friday deals you need to know about without the fluff WIRED2 uur geledenHexClad Pans Black Friday Sale: Save Up to $70 (2026) WIRED2 uur geledenOura Ring 5 Is $100 Off This Black Friday and Cyber Week (2026) Latest from TechRadar3 uur geledenI tried 20+ Android TV VPNs this year and these are the ones I’d save on this Black Friday — VPNs for beginners, 4K streaming, and good savings CNET3 uur geledenI Love This Fender Speaker for Its Looks and Its Bass, and It’s Still $45 Off After Black Friday WIRED3 uur geledenAir Purifier Black Friday Sale: Levoit, Blueair (2026) Latest from TechRadar3 uur geledenBlack Friday MacBook deals 2026: even bigger savings on MacBook Neo, MacBook Pro M6, and the new PROLED MacBook Pros as Cyber Monday draws near WIRED3 uur geledenThe Best Black Friday MacBook Deals Take Up to $300 Off The Verge3 uur geledenA tech girlie’s Black Friday guide to fabulous nails WIRED3 uur geledenThe Best Black Friday Action Camera Deals (2026) Latest from Windows Central4 uur geledenBought a new PC or monitor on Black Friday? Don't plug it into a cheap power strip Latest from TechRadar4 uur geledenHere’s the best Black Friday MacBook Air deal available right now Latest from TechRadar4 uur geledenI've reviewed a whole host of docking stations — here are the 8 worth buying in the holiday deals now Black Friday is done Latest from TechRadar4 uur geledenFastestVPN vs PrivadoVPN vs Windscribe: which cheap VPN should you buy this Black Friday? Latest from TechRadar4 uur geledenWalmart's Black Friday event ends tomorrow — see the 20 best last chance deals on TVs, appliances, laptops, headphones, ahead of Cyber Monday WIRED4 uur geledenBest JBL Black Friday Deals (2026): Save on JBL Flip 7 and More The Verge4 uur geledenBirdbuddy’s latest smart feeders are still at their low Black Friday prices
Soortgelijke bijdragen
🔍 Verwandte News

Auch interessante Nachrichten Closures in Python Explained by Tracing Through the Code

Thematisch verwandte Begriffe: Closures, Python, Explained, Tracing · 6 Treffer

Laden...

Video's zijn geladen...

Laden...

Bijdragen zijn geladen ...

Laden...

Video's zijn geladen...

Laden...

Bijdragen zijn geladen ...

Laden...

Video's zijn geladen...

Laden...

Bijdragen zijn geladen ...

Laden...

Video's zijn geladen...

Laden...

Bijdragen zijn geladen ...

Laden...

Video's zijn geladen...

💬 Reacties worden geladen…
Trek om te vernieuwen
Widgets & Topics
Loading widgets…
Nächster Beitrag