Skip to content

GrapaPy (Python) Use Cases

GrapaPy brings the power of Grapa to Python users, making advanced data processing, parallelism, and language experimentation accessible from Python. All examples below are verified to use the real GrapaPy API and will run as shown in the test suite and notebook.

See Also: - Python Integration Guide - Python-to-Grapa Migration Guide - Getting Started - Examples

Migration Tips for Python Users

Key Differences and Tips: - Use $global for persistent objects (file handles, tables, etc.)—local variables are lost between calls. - No for/foreach loops—use while for iteration. - No try/catch—check for $ERR return values and handle errors explicitly. - Use [] for list/array access, not .getfield() (which is for files/tables). - Use .map(), .reduce(), .filter() as methods on arrays/lists, not as global functions. - Every statement and block must end with a semicolon (;). - Block comments (/* ... */) and line comments (// ...) are both supported. # comments are not supported. - Explicit type conversion is required for results (e.g., .str(), .int(), .float()). - No implicit truthy/falsy—use explicit boolean checks. - No attribute-style access for dict/list keys—use [] or .getfield() for files/tables. - See the upcoming Python-to-Grapa Migration Guide for a full mapping and more examples.

GrapaPy provides direct access to Grapa's powerful Unicode-aware grep functionality, making it ideal for text processing tasks that require advanced pattern matching and Unicode handling.

Example: Log file analysis

import grapapy

# Analyze log files for errors and warnings
log_content = """
2024-01-15 10:30:15 INFO: Application started
2024-01-15 10:31:22 ERROR: Database connection failed
2024-01-15 10:32:45 WARNING: High memory usage detected
2024-01-15 10:33:12 INFO: User login successful
2024-01-15 10:34:01 ERROR: File not found: config.xml
"""

# Extract all error messages
errors = grapapy.grep(log_content, "ERROR:.*", "o")
print("Errors:", errors)
# Output: ['ERROR: Database connection failed', 'ERROR: File not found: config.xml']

# Extract timestamps for warnings
warnings = grapapy.grep(log_content, "\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2} WARNING:.*")
print("Warnings:", warnings)
# Output: ['2024-01-15 10:32:45 WARNING: High memory usage detected']

# Case-insensitive search for specific patterns
info_messages = grapapy.grep(log_content, "application|user", "i")
print("Info messages:", info_messages)
# Output: ['2024-01-15 10:30:15 INFO: Application started', '2024-01-15 10:33:12 INFO: User login successful']

Example: Unicode text processing

import grapapy

# Process international text with Unicode normalization
text = "café naïve résumé naïve café"

# Normalized search (matches accented characters)
matches = grapapy.grep(text, "cafe", "i", "", "NFD")
print("Normalized matches:", matches)
# Output: ['café', 'café']

# Extract all words with diacritics
accented_words = grapapy.grep(text, "\\w*[àáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ]\\w*", "o")
print("Accented words:", accented_words)
# Output: ['café', 'naïve', 'résumé', 'naïve', 'café']

Example: Data extraction from structured text

import grapapy

# Extract structured data from text
data_text = """
Name: John Doe, Age: 30, City: New York
Name: Jane Smith, Age: 25, City: Los Angeles
Name: Bob Johnson, Age: 35, City: Chicago
"""

# Extract all names
names = grapapy.grep(data_text, "Name: ([^,]+)", "o")
print("Names:", names)
# Output: ['John Doe', 'Jane Smith', 'Bob Johnson']

# Extract all ages
ages = grapapy.grep(data_text, "Age: (\\d+)", "o")
print("Ages:", ages)
# Output: ['30', '25', '35']

# Extract all cities
cities = grapapy.grep(data_text, "City: ([^\\n]+)", "o")
print("Cities:", cities)
# Output: ['New York', 'Los Angeles', 'Chicago']

Advanced Features: - Unicode normalization: Support for NFC, NFD, NFKC, NFKD normalization forms - Case-insensitive matching: Built-in support for Unicode case folding: - Regex engine: Full PCRE2 regex support with advanced features - Performance: Direct C++ implementation for maximum speed - Thread safety: Safe for use in multi-threaded Python applications


1. ETL / Data Engineering (Verified)

Example: Count lines in multiple CSV files

import grapapy
xy = grapapy.grapa()

files = ["data1.csv", "data2.csv", "data3.csv"]
total_lines = 0

# Initialize file system once (works in both execution modes)
xy.eval("$global.fs = $file();")

for file in files:
    # Use parameterized execution - fs persists because it's in global namespace
    content = xy.eval("fs.get(filename);", {"filename": file})
    if content:
        total_lines += len(str(content).split("\n"))
print(f"Total lines: {total_lines}")

Migration Tip: Use GrapaPy for file I/O and text processing instead of loading all data into memory with pandas.


2. Compiler/BNF Learning (Verified)

Example: Evaluate arithmetic expressions

import grapapy
xy = grapapy.grapa()

expressions = ["2+3*4", "(1+2)*3", "10/2+5"]
for expr in expressions:
    result = xy.eval(expr + ";")
    print(f"{expr} = {result}")

Example: Call Python from Grapa

def pyfunc(x):
    print(f"Python saw: {x}")
    return x * 2

import grapapy
xy = grapapy.grapa()
xy.eval("$this.pyfunc = op(x=0){$py().eval('pyfunc', {'x':$local.'x'});};")
xy.eval("pyfunc(5);")  # Output: Python saw: 5


3. High-Precision Math & Scientific Computing (Verified)

Example: Unlimited precision math

import grapapy
xy = grapapy.grapa()

result = xy.eval("12345678901234567890 * 98765432109876543210;")
print(result)  # Arbitrary precision

Example: Use GrapaPy for float math

import grapapy
xy = grapapy.grapa()

result = xy.eval("3.14159265358979323846264338327950288419716939937510 * 2;")
print(result)


4. Parallel/Concurrent Programming (Verified)

Note: GrapaPy is fully thread safe, but if you share mutable state between threads, you are responsible for the logic. Use a $thread() lock object if needed, or prefer immutable data and thread-local variables. See Threading and Locking for examples and best practices.

Example: Process a list of numbers

import grapapy
xy = grapapy.grapa()

data = list(range(10))
results = []
for item in data:
    result = xy.eval("item * 2;", {"item": item})
    results.append(result)
print(results)


5. Web/Data Scraping & Automation (Verified)

Example: Use Python requests for web scraping, process with GrapaPy

import grapapy
import requests
xy = grapapy.grapa()

url = "https://example.com"
response = requests.get(url)
if response.status_code == 200:
    content = response.text
    # Find all lines containing 'Example'
    matches = xy.eval("content.grep('Example');", {"content": content})
    print(matches)


6. Database & File System Integration (Verified)

Example: File system operations

import grapapy
xy = grapapy.grapa()

# Initialize file system (works in both execution modes)
xy.eval("$global.fs = $file();")

# Use file system - variables persist automatically in direct execution
xy.eval("fs.set('test.txt', 'Hello World!');")
content = xy.eval("fs.get('test.txt');")
print(content)

Example: Table operations

import grapapy
xy = grapapy.grapa()

# Initialize table (works in both execution modes)
xy.eval("$global.table = {}.table('ROW');")

# Use table - variables persist automatically in direct execution
xy.eval("table.mkfield('name', 'STR', 'VAR');")
xy.eval("table.set('user1', 'Alice', 'name');")
name = xy.eval("table.get('user1', 'name');")
print(name)


7. Education & Prototyping (Verified)

Example: Define and call a Grapa function from Python

import grapapy
xy = grapapy.grapa()

# Initialize function (works in both execution modes)
xy.eval("$global.square = op(x=0){x*x;};")

# Call function - variables persist automatically in direct execution
result = xy.eval("square(7);")
print(result)  # 49

Example: Grapa calling back into Python

def pytrace(n):
    print(f"trace: {n}")
    return n

import grapapy
xy = grapapy.grapa()
xy.eval("$this.pytrace = op(n=0){$py().eval('pytrace', {'n':$local.'n'});};")
xy.eval("pytrace(42);")


All examples above are verified to use only the real GrapaPy API and will run as shown in the test suite and notebook.