Close Menu

    Subscribe to Updates

    Get the latest creative news from FooBar about art, design and business.

    What's Hot

    Honda CR-V Hybrid Lineup Expanded in Malaysia From RM178,200

    vivo V70 – Top 7 Flagship Features You Will Love

    Apple iPad Air with M4 Officially Launches in Malaysia From RM2,799

    Facebook X (Twitter) Instagram
    • Artificial Intelligence
    • Business Technology
    • Cryptocurrency
    • Gadgets
    • Gaming
    • Health
    • Software and Apps
    • Technology
    Facebook X (Twitter) Instagram Pinterest Vimeo
    Tech AI Verse
    • Home
    • Artificial Intelligence

      What the polls say about how Americans are using AI

      February 27, 2026

      Tensions between the Pentagon and AI giant Anthropic reach a boiling point

      February 21, 2026

      Read the extended transcript: President Donald Trump interviewed by ‘NBC Nightly News’ anchor Tom Llamas

      February 6, 2026

      Stocks and bitcoin sink as investors dump software company shares

      February 4, 2026

      AI, crypto and Trump super PACs stash millions to spend on the midterms

      February 2, 2026
    • Business

      Weighing up the enterprise risks of neocloud providers

      March 3, 2026

      A stolen Gemini API key turned a $180 bill into $82,000 in two days

      March 3, 2026

      These ultra-budget laptops “include” 1.2TB storage, but most of it is OneDrive trial space

      March 1, 2026

      FCC approves the merger of cable giants Cox and Charter

      February 28, 2026

      Finding value with AI and Industry 5.0 transformation

      February 28, 2026
    • Crypto

      Strait of Hormuz Shutdown Shakes Asian Energy Markets

      March 3, 2026

      Wall Street’s Inflation Alarm From Iran — What It Means for Crypto

      March 3, 2026

      Ethereum Price Prediction: What To Expect From ETH In March 2026

      March 3, 2026

      Was Bitcoin Hijacked? How Institutional Interests Shaped Its Narrative Since 2015

      March 3, 2026

      XRP Whales Now Hold 83.7% of All Supply – What’s Next For Price?

      March 3, 2026
    • Technology

      Spotify’s new feature makes it easier to find popular audiobooks

      March 3, 2026

      This portable JBL Grip Bluetooth speaker is so good at 20% off

      March 3, 2026

      ‘AI’ could dox your anonymous posts

      March 3, 2026

      Microsoft says new Teams location feature isn’t for ’employee tracking’

      March 3, 2026

      OpenAI got ‘sloppy’ about the wrong thing

      March 3, 2026
    • Others
      • Gadgets
      • Gaming
      • Health
      • Software and Apps
    Check BMI
    Tech AI Verse
    You are at:Home»Technology»Show HN: Localscope–Limit scope of Python functions for reproducible execution
    Technology

    Show HN: Localscope–Limit scope of Python functions for reproducible execution

    TechAiVerseBy TechAiVerseMarch 17, 2025No Comments4 Mins Read2 Views
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    Share
    Facebook Twitter LinkedIn Pinterest WhatsApp Email

    Show HN: Localscope–Limit scope of Python functions for reproducible execution

    Toggle table of contents sidebar





    Have you ever hunted bugs caused by accidentally using a global variable in a function in a Jupyter notebook? Have you ever scratched your head because your code broke after restarting the Python kernel? localscope can help by restricting the variables a function can access.

    >>> from localscope import localscope
    >>>
    >>> a = 'hello world'
    >>>
    >>> @localscope
    ... def print_a():
    ...     print(a)
    Traceback (most recent call last):
      ...
    localscope.LocalscopeException: `a` is not a permitted global (file "...",
       line 1, in print_a)
    

    See the Interface section for an exhaustive list of options and the Motivation and Example for a more detailed example.

    Installation#

    Interface#

    localscope.localscope(func: function | code | None = None, *, predicate: Callable | None = None, allowed: Iterable[str] | str | None = None, allow_closure: bool = False)#

    Restrict the scope of a callable to local variables to avoid unintentional
    information ingress.

    Parameters:
    • func – Callable whose scope to restrict.

    • predicate – Predicate to determine whether a global variable is allowed in the
      scope. Defaults to allow any module.

    • allowed – Names of globals that are allowed to enter the scope.

    • allow_closure – Allow access to non-local variables from the enclosing scope.

    localscope.mfc#

    Decorator allowing modules, functions, and classes to enter
    the local scope.

    Examples

    Basic example demonstrating the functionality of localscope.

    >>> from localscope import localscope
    >>>
    >>> a = 'hello world'
    >>>
    >>> @localscope
    ... def print_a():
    ...     print(a)
    Traceback (most recent call last):
    ...
    localscope.LocalscopeException: `a` is not a permitted global (file "...",
        line 1, in print_a)
    

    The scope of a function can be extended by providing an iterable of allowed
    variable names or a string of space-separated allowed variable names.

    >>> a = 'hello world'
    >>>
    >>> @localscope(allowed=['a'])
    ... def print_a():
    ...     print(a)
    >>>
    >>> print_a()
    hello world
    

    The predicate keyword argument can be used to control which values are allowed
    to enter the scope (by default, only modules may be used in functions).

    >>> a = 'hello world'
    >>>
    >>> @localscope(predicate=lambda x: isinstance(x, str))
    ... def print_a():
    ...     print(a)
    >>>
    >>> print_a()
    hello world
    

    Localscope is strict by default, but localscope.mfc can be used to allow
    modules, functions, and classes to enter the function scope: a common use case
    in notebooks.

    >>> class MyClass:
    ...     pass
    >>>
    >>> @localscope.mfc
    ... def create_instance():
    ...     return MyClass()
    >>>
    >>> create_instance()
    
    

    Notes

    The localscope decorator analyses the decorated function at the time of
    declaration because static analysis has a minimal impact on performance and it
    is easier to implement.

    This also ensures localscope does not affect how your code runs in any way.

    >>> def my_func():
    ...     pass
    >>>
    >>> my_func is localscope(my_func)
    True
    

    Motivation and Example#

    Interactive python sessions are outstanding tools for analysing data, generating visualisations, and training machine learning models. However, the interactive nature allows global variables to leak into the scope of functions accidentally, leading to unexpected behaviour. For example, suppose you are evaluating the mean squared error between two lists of numbers, including a scale factor sigma.

    >>> sigma = 7
    >>> # [other notebook cells and bits of code]
    >>> xs = [1, 2, 3]
    >>> ys = [4, 5, 6]
    >>> mse = sum(((x - y) / sigma) ** 2 for x, y in zip(xs, ys))
    >>> mse
    0.55102...
    

    Everything works nicely, and you package the code in a function for later use but forget about the scale factor introduced earlier in the notebook.

    >>> def evaluate_mse(xs, ys):  # missing argument sigma
    ...     return sum(((x - y) / sigma) ** 2 for x, y in zip(xs, ys))
    >>>
    >>> mse = evaluate_mse(xs, ys)
    >>> mse
    0.55102...
    

    The variable sigma is obtained from the global scope, and the code executes without any issue. But the output is affected by changing the value of sigma.

    >>> sigma = 13
    >>> evaluate_mse(xs, ys)
    0.15976...
    

    This example may seem contrived. But unintended information leakage from the global scope to the local function scope often leads to unreproducible results, hours spent debugging, and many kernel restarts to identify the source of the problem. Localscope fixes this problem by restricting the allowed scope.

    >>> @localscope
    ... def evaluate_mse(xs, ys):  # missing argument sigma
    ...     return sum(((x - y) / sigma) ** 2 for x, y in zip(xs, ys))
    Traceback (most recent call last):
      ...
    localscope.LocalscopeException: `sigma` is not a permitted global (file "...",
       line 3, in )
    
    Share. Facebook Twitter Pinterest LinkedIn Reddit WhatsApp Telegram Email
    Previous ArticleDarker Than a Dark Pool? Welcome to Wall Street’s ‘Private Rooms’
    Next Article Zynga teams with Fast & Furious for year-long event series in CSR2
    TechAiVerse
    • Website

    Jonathan is a tech enthusiast and the mind behind Tech AI Verse. With a passion for artificial intelligence, consumer tech, and emerging innovations, he deliver clear, insightful content to keep readers informed. From cutting-edge gadgets to AI advancements and cryptocurrency trends, Jonathan breaks down complex topics to make technology accessible to all.

    Related Posts

    Spotify’s new feature makes it easier to find popular audiobooks

    March 3, 2026

    This portable JBL Grip Bluetooth speaker is so good at 20% off

    March 3, 2026

    ‘AI’ could dox your anonymous posts

    March 3, 2026
    Leave A Reply Cancel Reply

    Top Posts

    Ping, You’ve Got Whale: AI detection system alerts ships of whales in their path

    April 22, 2025703 Views

    Lumo vs. Duck AI: Which AI is Better for Your Privacy?

    July 31, 2025286 Views

    6.7 Cummins Lifter Failure: What Years Are Affected (And Possible Fixes)

    April 14, 2025164 Views

    6 Best MagSafe Phone Grips (2025), Tested and Reviewed

    April 6, 2025124 Views
    Don't Miss
    Gadgets March 4, 2026

    Honda CR-V Hybrid Lineup Expanded in Malaysia From RM178,200

    Honda CR-V Hybrid Lineup Expanded in Malaysia From RM178,200 Honda Malaysia has officially launched the…

    vivo V70 – Top 7 Flagship Features You Will Love

    Apple iPad Air with M4 Officially Launches in Malaysia From RM2,799

    Apple Launches iPhone 17e in Malaysia from RM2,999

    Stay In Touch
    • Facebook
    • Twitter
    • Pinterest
    • Instagram
    • YouTube
    • Vimeo

    Subscribe to Updates

    Get the latest creative news from SmartMag about art & design.

    About Us
    About Us

    Welcome to Tech AI Verse, your go-to destination for everything technology! We bring you the latest news, trends, and insights from the ever-evolving world of tech. Our coverage spans across global technology industry updates, artificial intelligence advancements, machine learning ethics, and automation innovations. Stay connected with us as we explore the limitless possibilities of technology!

    Facebook X (Twitter) Pinterest YouTube WhatsApp
    Our Picks

    Honda CR-V Hybrid Lineup Expanded in Malaysia From RM178,200

    March 4, 20262 Views

    vivo V70 – Top 7 Flagship Features You Will Love

    March 4, 20262 Views

    Apple iPad Air with M4 Officially Launches in Malaysia From RM2,799

    March 4, 20262 Views
    Most Popular

    7 Best Kids Bikes (2025): Mountain, Balance, Pedal, Coaster

    March 13, 20250 Views

    VTOMAN FlashSpeed 1500: Plenty Of Power For All Your Gear

    March 13, 20250 Views

    Best TV Antenna of 2025

    March 13, 20250 Views
    © 2026 TechAiVerse. Designed by Divya Tech.
    • Home
    • About Us
    • Contact Us
    • Privacy Policy
    • Terms & Conditions

    Type above and press Enter to search. Press Esc to cancel.