Skip to content

Commit cd25bb8

Browse files
committed
Add docs
1 parent d1de36b commit cd25bb8

2 files changed

Lines changed: 38 additions & 0 deletions

File tree

_docs_src/mkdocs.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ nav:
2222
- Class & Static Methods; Functions: static-methods.md
2323
- Miscellaneous:
2424
- Auto-generating bindings: auto-gen-bindings.md
25+
- Attributes -- py_fun_name: py_fun_name.md
2526
- CLI Options: cli-options.md
2627
- Converting `pyobjects` to OCaml types: of-pyobject.md
2728
- Embedding Python source: embedding-python.md

_docs_src/src/py_fun_name.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Attributes
2+
3+
You can attach certain attributes to your value specifications to change their behavior.
4+
5+
Currently, the only recognized attribute is `py_fun_name`.
6+
7+
You can use it to bind a Python method to a differently named OCaml function.
8+
9+
## Example
10+
11+
For example, rather than having a `Cat.__init__` method to call from the OCaml side (i.e., to make a new Python `Cat` object), you can bind the Python `__init__` function to something more idiomatic like `create` or whatever you want.
12+
13+
```ocaml
14+
val create : t -> ...
15+
[@@py_fun_name __init__]
16+
```
17+
18+
Another common use for this is to bind the Python `__str__` method for a class to `to_string` on the OCaml side.
19+
20+
You can do this with any function. One reason is that you may want to have some type safety with a polymorphic Python function. While you could pass in [Py.Object.t](https://mooreryan.github.io/ocaml_python_bindgen/types/#pytypes) directly, you could also use attributes to bind multiple OCaml functions to the same Python method. E.g.,
21+
22+
```ocaml
23+
val eat : t -> num_mice:int -> unit -> unit
24+
25+
val eat_part : t -> num_mice:float -> unit -> unit
26+
[@@py_fun_name eat]
27+
```
28+
29+
In this case, we have one `eat` function for `int` and one for `float`.
30+
31+
## Full example
32+
33+
For a full working example see the [attributes](https://github.com/mooreryan/ocaml_python_bindgen/tree/main/examples/attributes) example on GitHub.
34+
35+
## Warning
36+
37+
If you specify the `py_fun_name` more than once, it will do something wonky. Eventually, the program will treat this as an error, but for now, it is on you to avoid doing it.

0 commit comments

Comments
 (0)