### Start Jurigged Live REPL Source: https://github.com/breuleux/jurigged/blob/master/README.md Launches jurigged without a script, starting an interactive live REPL session. ```bash python -m jurigged OR jurigged ``` -------------------------------- ### Install Jurigged Source: https://github.com/breuleux/jurigged/blob/master/README.md Installs the jurigged package using pip. For the develoop feature, install with the 'develoop' extra. ```bash pip install jurigged ``` ```bash pip install jurigged[develoop] ``` -------------------------------- ### Programmatically Watch Files with Jurigged API Source: https://github.com/breuleux/jurigged/blob/master/README.md Demonstrates how to use the `jurigged.watch()` function to programmatically start watching for file changes. This can be used as an alternative to command-line usage and is compatible with environments like IPython and Jupyter. By default, it watches files in the current directory, but specific files or all files can be watched using arguments. ```python import jurigged jurigged.watch() # To watch a specific file: jurigged.watch("script.py") # To watch all modules: jurigged.watch("/") ``` -------------------------------- ### Create File Filters and Event Sources with Jurigged Utilities Source: https://context7.com/breuleux/jurigged/llms.txt Provides examples of using `glob_filter`, `or_filter`, and `EventSource` from `jurigged.utils`. `glob_filter` creates functions to match file paths against glob patterns, while `or_filter` combines multiple filters. `EventSource` allows for registering listeners that are notified when an event is emitted, with an option to save and replay historical events. ```python from jurigged.utils import glob_filter, or_filter, EventSource # Create a filter for specific file patterns filter_py = glob_filter("./*.py") # Current directory .py files filter_src = glob_filter("./src/*.py") # Source directory filter_all = glob_filter("/") # All files filter_home = glob_filter("~/projects/*") # Home directory expansion # Check if a file matches if filter_py("/path/to/script.py"): print("File matches pattern") # Combine multiple filters combined = or_filter([ glob_filter("./src/*.py"), glob_filter("./lib/*.py"), glob_filter("./tests/*.py") ]) # Custom event source for notifications events = EventSource() def listener1(message): print(f"Listener 1: {message}") def listener2(message): print(f"Listener 2: {message}") events.register(listener1) events.register(listener2) events.emit("Something happened") # Notifies all listeners # Event source with history (new listeners get past events) events_with_history = EventSource(save_history=True) events_with_history.emit("Event 1") events_with_history.emit("Event 2") # New listener receives historical events events_with_history.register(lambda msg: print(f"Got: {msg}")) # Output: Got: Event 1, Got: Event 2 ``` -------------------------------- ### Watcher Class for File System Monitoring Source: https://context7.com/breuleux/jurigged/llms.txt The `Watcher` class provides direct access to jurigged's file watching mechanism. It monitors file system changes and triggers updates. You can configure settings like debounce time and polling mode, and register callbacks for pre/post refresh events. The watcher can be manually controlled to start, stop, or join the watching thread. ```python from jurigged.live import Watcher from jurigged import registry # Create a watcher with custom settings watcher = Watcher( registry=registry, debounce=0.1, # Wait 100ms before processing changes poll=False # Use OS native file watching ) # Use polling mode for problematic editors watcher = Watcher( registry=registry, poll=1.0 # Poll every 1 second ) # Register callbacks for pre/post refresh def before_refresh(path, codefile): print(f"About to refresh: {path}") def after_refresh(path, codefile): print(f"Refreshed: {path}") watcher.prerun.register(before_refresh) watcher.postrun.register(after_refresh) # Manual control watcher.start() # Start watching watcher.stop() # Stop watching watcher.join() # Wait for thread # Manually trigger refresh watcher.refresh("/path/to/file.py") ``` -------------------------------- ### Jurigged Command-Line Help Source: https://github.com/breuleux/jurigged/blob/master/README.md Displays the full help message for the jurigged command-line tool, outlining available arguments and options. ```bash usage: jurigged [-h] [--interactive] [--watch PATH] [--debounce DEBOUNCE] [--poll POLL] [-m MODULE] [--dev] [--verbose] [--version] [SCRIPT] ... Run a Python script so that it is live-editable. positional arguments: SCRIPT Path to the script to run ... Script arguments optional arguments: -h, --help show this help message and exit --interactive, -i Run an interactive session after the program ends --watch PATH, -w PATH Wildcard path/directory for which files to watch --debounce DEBOUNCE, -d DEBOUNCE Interval to wait for to refresh a modified file, in seconds --poll POLL Poll for changes using the given interval -m MODULE Module or module:function to run --dev Inject jurigged.loop.__ in builtins --verbose, -v Show watched files and changes as they happen --version Print version ``` -------------------------------- ### Implement Custom __conform__ Protocol for Hot-Reloading Source: https://context7.com/breuleux/jurigged/llms.txt Demonstrates how to implement the `__conform__` method in a custom class to enable hot-reloading for objects that wrap or transform functions. This allows code transformers to receive updates when source code changes, ensuring that compiled or transformed functions stay current. The `__conform__` method is automatically called by jurigged when the source code of a decorated function is modified. ```python import types class JITCompiledFunction: """Example: A custom wrapper that needs to update when source changes.""" __slots__ = ("code", "compiled_fn", "original_fn") def __init__(self, fn): self.original_fn = fn self.code = fn.__code__ # Must be in __slots__ for jurigged to find it self.compiled_fn = self._compile(fn) def _compile(self, fn): # Your JIT compilation logic here return fn # Placeholder def __conform__(self, new_code): """Called by jurigged when the original function's code changes.""" if new_code is None: # Function is being deleted self.compiled_fn = None return if isinstance(new_code, types.FunctionType): new_code = new_code.__code__ # Re-compile with new code self.code = new_code # Create a new function object with updated code new_fn = types.FunctionType( new_code, self.original_fn.__globals__, self.original_fn.__name__ ) self.compiled_fn = self._compile(new_fn) def __call__(self, *args, **kwargs): return self.compiled_fn(*args, **kwargs) # Usage @JITCompiledFunction def hot_function(x): return x * 2 # When hot_function's source is modified, # JITCompiledFunction.__conform__ is called automatically ``` -------------------------------- ### Command-line Live Coding with Jurigged Source: https://context7.com/breuleux/jurigged/llms.txt Control jurigged's live-coding behavior from the command line. Options include looping on module execution, looping only on errors, looping multiple functions, and specifying the interface. ```bash jurigged --loop mymodule:process_data script.py jurigged --xloop process_data script.py jurigged --loop func1 --loop func2 script.py jurigged --loop-interface basic --loop my_function script.py ``` -------------------------------- ### Run Python Script with Jurigged Source: https://github.com/breuleux/jurigged/blob/master/README.md Executes a Python script using jurigged, enabling live code updates. The '-v' flag provides verbose output. ```bash python -m jurigged -v script.py OR jurigged -v script.py ``` -------------------------------- ### Jurigged Develoop: Basic Interface Source: https://github.com/breuleux/jurigged/blob/master/README.md Applies a basic interface to the jurigged develoop feature, which is useful when interacting with stdin or using pdb. ```python @__.loop(interface="basic") ``` -------------------------------- ### Run Python Scripts with Jurigged CLI Source: https://context7.com/breuleux/jurigged/llms.txt Execute Python scripts with hot-reloading enabled using the `jurigged` command or `python -m jurigged`. This CLI supports various options for customization, including verbose mode, custom watch patterns, debounce intervals, polling, and interactive modes. ```bash # Basic usage - run a script with hot-reloading jurigged script.py # Verbose mode - see watched files and updates jurigged -v script.py # Run a module instead of a script jurigged -m mymodule # Run a specific function from a module jurigged -m mymodule:main_function # Watch specific paths (default is current directory) jurigged -w /path/to/watch -w ./other/path script.py # Set debounce interval (default 0.05s) jurigged -d 0.1 script.py # Use polling instead of OS file watching (useful for some editors) jurigged --poll 1.0 script.py # Start interactive REPL with hot-reloading jurigged # Interactive mode after script execution jurigged -i script.py ``` -------------------------------- ### Programmatic Live Coding with Jurigged Decorators Source: https://context7.com/breuleux/jurigged/llms.txt Use decorators like `@loop` and `@xloop` to enable live coding for Python functions. These decorators automatically re-run functions when their source code changes. Different interfaces can be specified, including 'basic' for stdin/pdb and 'rich' for a richer terminal UI. ```python from jurigged.loop import loop, xloop @loop def my_function(x): """This function will loop on every call, re-running when code changes.""" result = x * 2 print(f"Result: {result}") return result @xloop def risky_function(data): """Normal execution until error, then enters develoop.""" return process(data) @loop(interface="basic") # Supports stdin and breakpoints def interactive_function(): user_input = input("Enter value: ") return int(user_input) @loop(interface="rich") # Rich terminal UI (default if rich is installed) def pretty_function(): return {"status": "ok"} # Develoop keyboard commands during execution: # r - manually re-run the function # a - abort current run (useful for infinite loops) # c - continue/exit the loop and proceed normally # q - quit the program entirely ``` -------------------------------- ### Hot Patching Functions with Jurigged Recoder Source: https://github.com/breuleux/jurigged/blob/master/README.md Illustrates how to use `jurigged.make_recoder` to create a recoder object for programmatically changing function behavior without modifying the original file. This enables hot patching and mocking. The changes can be applied temporarily using `patch` and reverted with `revert`, or permanently written to the file using `commit`. ```python from jurigged import make_recoder def f(x): return x * x assert f(2) == 4 # Change the behavior of the function, but not in the original file recoder = make_recoder(f) recoder.patch("def f(x): return x * x * x") assert f(2) == 8 # Revert changes recoder.revert() assert f(2) == 4 # OR: write the patch to the original file itself # recoder.commit() ``` -------------------------------- ### Interactive Function Development with Jurigged Develoop Source: https://context7.com/breuleux/jurigged/llms.txt The develoop feature provides an interactive development environment for iterating on individual functions. When enabled via the CLI, the specified function runs in a loop that automatically re-executes upon source code changes, with captured output and error handling. ```bash # Loop over a function - re-runs on every code change jurigged --loop process_data script.py ``` -------------------------------- ### Programmatically Enable Hot-Reloading with jurigged.watch() Source: https://context7.com/breuleux/jurigged/llms.txt Use the `jurigged.watch()` function to programmatically enable hot-reloading in your Python applications. This API allows for fine-grained control over file watching, logging, and the start/stop behavior of the watcher. ```python import jurigged # Watch all .py files in the current directory (default) watcher = jurigged.watch() # Watch a specific file watcher = jurigged.watch("script.py") # Watch all Python modules (entire sys.path) watcher = jurigged.watch("/") # Watch multiple patterns watcher = jurigged.watch(["./src/*.py", "./lib/*.py"]) # Custom logger to see updates (default prints to console) def my_logger(event): print(f"Code changed: {event}") watcher = jurigged.watch(logger=my_logger) # Disable automatic start (manual control) watcher = jurigged.watch(autostart=False) watcher.start() # Start watching watcher.stop() # Stop watching watcher.join() # Wait for watcher thread to finish # Configure debounce (delay before processing changes) watcher = jurigged.watch(debounce=0.1) # Use polling mode (for editors like vi) watcher = jurigged.watch(poll=1.0) # Example: Live development in Jupyter import jurigged jurigged.watch() # Now edit mymodule.py in your editor import mymodule mymodule.my_function() # Automatically uses updated code after save ``` -------------------------------- ### Customizing Python Function Transforms with __conform__ Source: https://github.com/breuleux/jurigged/blob/master/README.md This snippet demonstrates how to create a custom class to update a Python function's code object when the original source code changes. It utilizes the __conform__ method, which is called by jurigged when a code modification is detected. The original code must be stored in a __slots__ attribute for jurigged to find it. ```python class Custom: __slots__ = ("code",) def __init__(self, transformed_fn, code): self.code = code self.transformed_fn = transformed_fn def __conform__(self, new_code): if new_code is None: # Function is being deleted ... if isinstance(new_code, types.FunctionType): new_code = new_code.__code__ do_something(new_code) self.code = new_code ... transformed_fn.somefield = Custom(transformed_fn, orig_fn.__code__) ``` -------------------------------- ### Jurigged Develoop: Loop on Function Source: https://github.com/breuleux/jurigged/blob/master/README.md Uses jurigged's develoop feature to continuously re-run a specified function when its source code changes. The '--xloop' flag only re-runs if an exception occurs. ```bash # Loop over a function jurigged --loop function_name script.py jurigged --loop module_name:function_name script.py # Only stop on exceptions jurigged --xloop function_name script.py ``` -------------------------------- ### CodeFile API for Python Source Manipulation Source: https://context7.com/breuleux/jurigged/llms.txt The `CodeFile` API allows parsing and manipulating Python source files. It tracks the structure of a parsed file for surgical updates. You can create `CodeFile` objects, associate them with modules or namespaces, refresh from disk, commit changes, and register for change events. ```python from jurigged.codetools import CodeFile from jurigged import registry # Create a CodeFile from a file cf = CodeFile( filename="/path/to/module.py", module_name="mymodule" ) # Associate with a live module import mymodule cf.associate(mymodule) # Or associate with a dict (for exec contexts) namespace = {} cf.associate(namespace) # Refresh from disk (applies changes) cf.refresh() # Commit in-memory changes to disk cf.commit() # Check if file has been modified externally if cf.stale(): print("File changed on disk") # Access the module root root = cf.root # Walk all definitions for defn in cf.root.walk(): print(f"{defn.dotpath()} at line {defn.groundline}") # Register for change events def on_change(event): print(f"Change detected: {event}") cf.activity.register(on_change) # Using the global registry from jurigged import registry # Find a function in the registry cf, defn = registry.find(some_function) print(f"Found {defn.name} in {cf.filename}") # Find a class cf, defn = registry.find(SomeClass) # Find by module import mymodule cf, defn = registry.find(mymodule) # Get CodeFile at specific location cf, defn = registry.get_at("/path/to/file.py", lineno=42) ``` -------------------------------- ### Modify Function Behavior at Runtime with jurigged.make_recoder() Source: https://context7.com/breuleux/jurigged/llms.txt The `jurigged.make_recoder()` function creates a Recoder object for programmatically modifying function behavior at runtime. This enables hot-patching, mocking, and dynamic code changes, with the option to commit these changes back to the source file. ```python from jurigged import make_recoder # Original function def calculate(x, y): return x + y # Create a recoder for the function recoder = make_recoder(calculate) # Patch the function with new behavior recoder.patch("def calculate(x, y): return x * y") # Function is now modified result = calculate(3, 4) # Returns 12 instead of 7 # Revert to original behavior recoder.revert() result = calculate(3, 4) # Returns 7 again # Patch and commit changes to the source file recoder.patch("def calculate(x, y): return x - y") recoder.commit() # Writes changes to original file # For more complex patches (adding imports, helpers, etc.) recoder.patch_module(""" import math def calculate(x, y): return math.sqrt(x**2 + y**2) """) # Check recoder status print(recoder.status) # 'live', 'out-of-sync', or 'saved' # Listen for status changes def on_status_change(recoder, status): print(f"Recoder status: {status}") recoder.on_status.register(on_status_change) # Allow deleting the function recoder = make_recoder(calculate, deletable=True) recoder.patch("") # Deletes the function ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.