Install & Compatibility
Where this runs
tested against v0.1.3 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.920 runs
installs and imports cleanly · install 0.0s · import 0.000s · 19.2MB
glibcpy 3.10–3.920 runs
installs and imports cleanly · install 2.4s · import 0.000s · 20MB
17MB installed
● package 17MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
Visitor
✓ from visitor import Visitor
This quickstart demonstrates how to use the `Visitor` class to implement a simple JSON encoder. It defines a `JSONEncoder` class that inherits from `Visitor` and provides `visit_` methods for different Python types (list, dict, str, int, float). The `generic_visit` method acts as a fallback for unhandled types.
from visitor import Visitor
class JSONEncoder(Visitor):
def __init__(self):
self.output = []
def visit_list(self, obj):
self.output.append('[')
for item in obj:
self.visit(item)
self.output.append(',')
if len(obj) > 0: # Remove trailing comma if list is not empty
self.output.pop()
self.output.append(']')
def visit_dict(self, obj):
self.output.append('{')
for key, value in obj.items():
self.visit(key)
self.output.append(':')
self.visit(value)
self.output.append(',')
if len(obj) > 0: # Remove trailing comma if dict is not empty
self.output.pop()
self.output.append('}')
def visit_str(self, obj):
self.output.append(f'"{obj}"')
def visit_int(self, obj):
self.output.append(str(obj))
def visit_float(self, obj):
self.output.append(str(obj))
def generic_visit(self, obj):
# Fallback for types not explicitly handled, e.g., None, bool
self.output.append(str(obj).lower() if isinstance(obj, bool) else 'null' if obj is None else repr(obj))
def encode(self, obj):
self.output = []
self.visit(obj)
return ''.join(self.output)
# Example Usage:
data = {
'name': 'Alice',
'age': 30,
'isStudent': False,
'courses': ['Math', 'Science'],
'address': {'city': 'New York', 'zip': 10001},
'grades': [95, 88.5, 76],
'null_field': None
}
encoder = JSONEncoder()
json_string = encoder.encode(data)
print(json_string)
expected_output = '{"name":"Alice","age":30,"isStudent":false,"courses":["Math","Science"],"address":{"city":"New York","zip":10001},"grades":[95,88.5,76],"null_field":null}'
assert json_string == expected_output
print("Output matches expected JSON.")
Debug
Known issues
gotchaThe library has not been updated since May 2016, with version 0.1.3 being the latest. While the core visitor pattern implementation is stable, it means the library is not actively maintained and may not leverage newer Python features or address modern compatibility concerns.fixBe aware that the library is unmaintained. For new projects, consider implementing the visitor pattern manually or using a more actively developed library. If using this library, thorough testing with your target Python version is recommended.
affects: All versions (0.1.x)
gotchaThe documentation itself suggests that the library is so small you might be better off copying and pasting the source directly into your project. This further emphasizes its lack of active development and its minimal footprint.fixEvaluate whether including this as a dependency is necessary or if a direct copy of the source code (which is very small) might be more appropriate for your project's long-term maintenance strategy.
affects: All versions (0.1.x)
gotchaNaming a local file or module `visitor.py` can lead to a naming conflict, shadowing this installed library or the more common design pattern concept itself. This is a general Python footgun when using simple, descriptive names for modules.fixAvoid naming your own Python files or modules 'visitor.py' to prevent accidental shadowing. Always import with explicit names or aliases if conflicts arise, e.g., `import visitor as visitor_lib`.
affects: All versions (0.1.x)
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'visitor'
The 'visitor' library has not been installed in the current Python environment, or the environment is not correctly configured.
fixInstall the library using pip: `pip install visitor`
NameError: name 'when' is not defined
The `@when` decorator was used directly without importing it specifically or qualifying it with the `visitor` module prefix.
fixEither import the decorator specifically with `from visitor import when` or use it qualified as `@visitor.when`.
TypeError: <function_name>() takes 0 positional arguments but 1 was given
A function decorated with `@visitor.when` was defined to take no arguments, but the visitor dispatcher expects it to accept at least one argument (the visited object).
fixModify the visitor function to accept at least one argument for the visited object, for example: `def visit_type(node):`
NoMethodFound: No visitor method for <class 'int'>
The `visitor` dispatcher was called with an object of a specific type (e.g., `int`) for which no corresponding visitor function or method has been registered using the `@visitor.when` decorator.
fixDefine and decorate a function to handle the specific type, for example: `@visitor.when(int) def visit_int(node): pass`
Upgrade
Version history
0.1.3latest on PyPI · released May 18, 2016
Audit
Dependencies
No dependency data recorded yet.