Skip to content

Commit 52c198a

Browse files
authored
Doc: Use C-string literals where possible (#5549)
Missed from previous MR
1 parent b932635 commit 52c198a

File tree

8 files changed

+52
-65
lines changed

8 files changed

+52
-65
lines changed

README.md

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -146,15 +146,14 @@ Example program displaying the value of `sys.version` and the current user name:
146146
```rust
147147
use pyo3::prelude::*;
148148
use pyo3::types::IntoPyDict;
149-
use pyo3::ffi::c_str;
150149

151150
fn main() -> PyResult<()> {
152151
Python::attach(|py| {
153152
let sys = py.import("sys")?;
154153
let version: String = sys.getattr("version")?.extract()?;
155154

156155
let locals = [("os", py.import("os")?)].into_py_dict(py)?;
157-
let code = c_str!("os.getenv('USER') or os.getenv('USERNAME') or 'Unknown'");
156+
let code = c"os.getenv('USER') or os.getenv('USERNAME') or 'Unknown'";
158157
let user: String = py.eval(code, None, Some(&locals))?.extract()?;
159158

160159
println!("Hello {}, I'm Python {}", user, version);

guide/src/class.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1426,8 +1426,8 @@ impl pyo3::impl_::pyclass::PyClassImpl for MyClass {
14261426
type WeakRef = pyo3::impl_::pyclass::PyClassDummySlot;
14271427
type BaseNativeType = pyo3::PyAny;
14281428

1429-
const RAW_DOC: &'static std::ffi::CStr = pyo3::ffi::c_str!("...");
1430-
const DOC: &'static std::ffi::CStr = pyo3::ffi::c_str!("...");
1429+
const RAW_DOC: &'static std::ffi::CStr = c"...";
1430+
const DOC: &'static std::ffi::CStr = c"...";
14311431

14321432
fn items_iter() -> pyo3::impl_::pyclass::PyClassItemsIter {
14331433
use pyo3::impl_::pyclass::*;

guide/src/class/numeric.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -335,7 +335,7 @@ mod my_module {
335335
#[pymodule_export]
336336
use super::Number;
337337
}
338-
# const SCRIPT: &'static std::ffi::CStr = pyo3::ffi::c_str!(r#"
338+
# const SCRIPT: &'static std::ffi::CStr = cr#"
339339
# def hash_djb2(s: str):
340340
# n = Number(0)
341341
# five = Number(5)
@@ -384,7 +384,7 @@ mod my_module {
384384
# pass
385385
# assert Number(1337).__str__() == '1337'
386386
# assert Number(1337).__repr__() == 'Number(1337)'
387-
"#);
387+
"#;
388388

389389
#
390390
# use pyo3::PyTypeInfo;

guide/src/conversions/traits.md

Lines changed: 17 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,6 @@ the Python object, i.e. `obj.getattr("my_string")`, and call `extract()` on the
4646

4747
```rust
4848
use pyo3::prelude::*;
49-
use pyo3_ffi::c_str;
5049

5150
#[derive(FromPyObject)]
5251
struct RustyStruct {
@@ -57,11 +56,11 @@ struct RustyStruct {
5756
# Python::attach(|py| -> PyResult<()> {
5857
# let module = PyModule::from_code(
5958
# py,
60-
# c_str!("class Foo:
59+
# c"class Foo:
6160
# def __init__(self):
62-
# self.my_string = 'test'"),
63-
# c_str!("<string>"),
64-
# c_str!(""),
61+
# self.my_string = 'test'",
62+
# c"<string>",
63+
# c"",
6564
# )?;
6665
#
6766
# let class = module.getattr("Foo")?;
@@ -101,7 +100,6 @@ The argument passed to `getattr` and `get_item` can also be configured:
101100

102101
```rust
103102
use pyo3::prelude::*;
104-
use pyo3_ffi::c_str;
105103

106104
#[derive(FromPyObject)]
107105
struct RustyStruct {
@@ -115,12 +113,12 @@ struct RustyStruct {
115113
# Python::attach(|py| -> PyResult<()> {
116114
# let module = PyModule::from_code(
117115
# py,
118-
# c_str!("class Foo(dict):
116+
# c"class Foo(dict):
119117
# def __init__(self):
120118
# self.name = 'test'
121-
# self['key'] = 'test2'"),
122-
# c_str!("<string>"),
123-
# c_str!(""),
119+
# self['key'] = 'test2'",
120+
# c"<string>",
121+
# c"",
124122
# )?;
125123
#
126124
# let class = module.getattr("Foo")?;
@@ -157,7 +155,7 @@ struct RustyStruct {
157155
#
158156
# fn main() -> PyResult<()> {
159157
# Python::attach(|py| -> PyResult<()> {
160-
# let py_dict = py.eval(pyo3::ffi::c_str!("{'foo': 'foo', 'bar': 'bar', 'foobar': 'foobar'}"), None, None)?;
158+
# let py_dict = py.eval(c"{'foo': 'foo', 'bar': 'bar', 'foobar': 'foobar'}", None, None)?;
161159
# let rustystruct: RustyStruct = py_dict.extract()?;
162160
# assert_eq!(rustystruct.foo, "foo");
163161
# assert_eq!(rustystruct.bar, "bar");
@@ -265,7 +263,6 @@ attribute can be applied to single-field-variants.
265263

266264
```rust
267265
use pyo3::prelude::*;
268-
use pyo3_ffi::c_str;
269266

270267
#[derive(FromPyObject)]
271268
# #[derive(Debug)]
@@ -345,13 +342,13 @@ enum RustyEnum<'py> {
345342
# {
346343
# let module = PyModule::from_code(
347344
# py,
348-
# c_str!("class Foo(dict):
345+
# c"class Foo(dict):
349346
# def __init__(self):
350347
# self.x = 0
351348
# self.y = 1
352-
# self.z = 2"),
353-
# c_str!("<string>"),
354-
# c_str!(""),
349+
# self.z = 2",
350+
# c"<string>",
351+
# c"",
355352
# )?;
356353
#
357354
# let class = module.getattr("Foo")?;
@@ -370,12 +367,12 @@ enum RustyEnum<'py> {
370367
# {
371368
# let module = PyModule::from_code(
372369
# py,
373-
# c_str!("class Foo(dict):
370+
# c"class Foo(dict):
374371
# def __init__(self):
375372
# self.x = 3
376-
# self.y = 4"),
377-
# c_str!("<string>"),
378-
# c_str!(""),
373+
# self.y = 4",
374+
# c"<string>",
375+
# c"",
379376
# )?;
380377
#
381378
# let class = module.getattr("Foo")?;

guide/src/module.md

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -101,11 +101,10 @@ fn func() -> String {
101101
# Python::attach(|py| {
102102
# use pyo3::wrap_pymodule;
103103
# use pyo3::types::IntoPyDict;
104-
# use pyo3::ffi::c_str;
105104
# let parent_module = wrap_pymodule!(parent_module)(py);
106105
# let ctx = [("parent_module", parent_module)].into_py_dict(py).unwrap();
107106
#
108-
# py.run(c_str!("assert parent_module.child_module.func() == 'func'"), None, Some(&ctx)).unwrap();
107+
# py.run(c"assert parent_module.child_module.func() == 'func'", None, Some(&ctx)).unwrap();
109108
# })
110109
}
111110
```

guide/src/python-from-rust/calling-existing-code.md

Lines changed: 15 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -33,12 +33,11 @@ and return the evaluated value as a `Bound<'py, PyAny>` object.
3333

3434
```rust
3535
use pyo3::prelude::*;
36-
use pyo3::ffi::c_str;
3736

3837
# fn main() -> Result<(), ()> {
3938
Python::attach(|py| {
4039
let result = py
41-
.eval(c_str!("[i * 10 for i in range(5)]"), None, None)
40+
.eval(c"[i * 10 for i in range(5)]", None, None)
4241
.map_err(|e| {
4342
e.print_and_set_sys_last_vars(py);
4443
})?;
@@ -108,22 +107,21 @@ to this function!
108107

109108
```rust
110109
use pyo3::{prelude::*, types::IntoPyDict};
111-
use pyo3_ffi::c_str;
112110

113111
# fn main() -> PyResult<()> {
114112
Python::attach(|py| {
115113
let activators = PyModule::from_code(
116114
py,
117-
c_str!(r#"
115+
cr#"
118116
def relu(x):
119117
"""see https://en.wikipedia.org/wiki/Rectifier_(neural_networks)"""
120118
return max(0.0, x)
121119

122120
def leaky_relu(x, slope=0.01):
123121
return x if x >= 0 else x * slope
124-
"#),
125-
c_str!("activators.py"),
126-
c_str!("activators"),
122+
"#,
123+
c"activators.py",
124+
c"activators",
127125
)?;
128126
129127
let relu_result: f64 = activators.getattr("relu")?.call1((-1.0,))?.extract()?;
@@ -155,7 +153,6 @@ As an example, the below adds the module `foo` to the embedded interpreter:
155153
156154
```rust
157155
use pyo3::prelude::*;
158-
use pyo3::ffi::c_str;
159156
160157
#[pymodule]
161158
mod foo {
@@ -169,7 +166,7 @@ mod foo {
169166
170167
fn main() -> PyResult<()> {
171168
pyo3::append_to_inittab!(foo);
172-
Python::attach(|py| Python::run(py, c_str!("import foo; foo.add_one(6)"), None, None))
169+
Python::attach(|py| Python::run(py, c"import foo; foo.add_one(6)", None, None))
173170
}
174171
```
175172
@@ -180,7 +177,6 @@ and insert it manually into `sys.modules`:
180177
```rust
181178
use pyo3::prelude::*;
182179
use pyo3::types::PyDict;
183-
use pyo3::ffi::c_str;
184180
185181
#[pyfunction]
186182
pub fn add_one(x: i64) -> i64 {
@@ -201,7 +197,7 @@ fn main() -> PyResult<()> {
201197
py_modules.set_item("foo", foo_module)?;
202198
203199
// Now we can import + run our python code
204-
Python::run(py, c_str!("import foo; foo.add_one(6)"), None, None)
200+
Python::run(py, c"import foo; foo.add_one(6)", None, None)
205201
})
206202
}
207203
```
@@ -267,8 +263,8 @@ fn main() -> PyResult<()> {
267263
)));
268264
let py_app = c_str!(include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/python_app/app.py")));
269265
let from_python = Python::attach(|py| -> PyResult<Py<PyAny>> {
270-
PyModule::from_code(py, py_foo, c_str!("foo.py"), c_str!("utils.foo"))?;
271-
let app: Py<PyAny> = PyModule::from_code(py, py_app, c_str!("app.py"), c_str!(""))?
266+
PyModule::from_code(py, py_foo, c"foo.py", c"utils.foo")?;
267+
let app: Py<PyAny> = PyModule::from_code(py, py_app, c"app.py", c"")?
272268
.getattr("run")?
273269
.into();
274270
app.call0(py)
@@ -295,7 +291,6 @@ that directory is `/usr/share/python_app`).
295291
```rust,no_run
296292
use pyo3::prelude::*;
297293
use pyo3::types::PyList;
298-
use pyo3_ffi::c_str;
299294
use std::fs;
300295
use std::path::Path;
301296
use std::ffi::CString;
@@ -309,7 +304,7 @@ fn main() -> PyResult<()> {
309304
.getattr("path")?
310305
.cast_into::<PyList>()?;
311306
syspath.insert(0, path)?;
312-
let app: Py<PyAny> = PyModule::from_code(py, py_app.as_c_str(), c_str!("app.py"), c_str!(""))?
307+
let app: Py<PyAny> = PyModule::from_code(py, py_app.as_c_str(), c"app.py", c"")?
313308
.getattr("run")?
314309
.into();
315310
app.call0(py)
@@ -326,13 +321,12 @@ Use context managers by directly invoking `__enter__` and `__exit__`.
326321
327322
```rust
328323
use pyo3::prelude::*;
329-
use pyo3::ffi::c_str;
330324
331325
fn main() {
332326
Python::attach(|py| {
333327
let custom_manager = PyModule::from_code(
334328
py,
335-
c_str!(r#"
329+
cr#"
336330
class House(object):
337331
def __init__(self, address):
338332
self.address = address
@@ -344,9 +338,9 @@ class House(object):
344338
else:
345339
print(f"Thank you for visiting {self.address}, come again soon!")
346340

347-
"#),
348-
c_str!("house.py"),
349-
c_str!("house"),
341+
"#,
342+
c"house.py",
343+
c"house",
350344
)
351345
.unwrap();
352346
@@ -355,7 +349,7 @@ class House(object):
355349
356350
house.call_method0("__enter__").unwrap();
357351
358-
let result = py.eval(c_str!("undefined_variable + 1"), None, None);
352+
let result = py.eval(c"undefined_variable + 1", None, None);
359353
360354
// If the eval threw an exception we'll pass it through to the context manager.
361355
// Otherwise, __exit__ is called with empty arguments (Python "None").

guide/src/python-from-rust/function-calls.md

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ The example below calls a Python function behind a `Py<PyAny>` reference:
1919
```rust
2020
use pyo3::prelude::*;
2121
use pyo3::types::PyTuple;
22-
use pyo3_ffi::c_str;
2322

2423
fn main() -> PyResult<()> {
2524
let arg1 = "arg1";
@@ -29,15 +28,15 @@ fn main() -> PyResult<()> {
2928
Python::attach(|py| {
3029
let fun: Py<PyAny> = PyModule::from_code(
3130
py,
32-
c_str!("def example(*args, **kwargs):
31+
c"def example(*args, **kwargs):
3332
if args != ():
3433
print('called with args', args)
3534
if kwargs != {}:
3635
print('called with kwargs', kwargs)
3736
if args == () and kwargs == {}:
38-
print('called with no arguments')"),
39-
c_str!("example.py"),
40-
c_str!(""),
37+
print('called with no arguments')",
38+
c"example.py",
39+
c"",
4140
)?
4241
.getattr("example")?
4342
.into();
@@ -65,7 +64,6 @@ For the `call` and `call_method` APIs, `kwargs` are `Option<&Bound<'py, PyDict>>
6564
use pyo3::prelude::*;
6665
use pyo3::types::{PyDict, IntoPyDict};
6766
use std::collections::HashMap;
68-
use pyo3::ffi::c_str;
6967

7068
fn main() -> PyResult<()> {
7169
let key1 = "key1";
@@ -76,15 +74,15 @@ fn main() -> PyResult<()> {
7674
Python::attach(|py| {
7775
let fun: Py<PyAny> = PyModule::from_code(
7876
py,
79-
c_str!("def example(*args, **kwargs):
77+
c"def example(*args, **kwargs):
8078
if args != ():
8179
print('called with args', args)
8280
if kwargs != {}:
8381
print('called with kwargs', kwargs)
8482
if args == () and kwargs == {}:
85-
print('called with no arguments')"),
86-
c_str!("example.py"),
87-
c_str!(""),
83+
print('called with no arguments')",
84+
c"example.py",
85+
c"",
8886
)?
8987
.getattr("example")?
9088
.into();

pyo3-ffi/README.md

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -73,8 +73,8 @@ use pyo3_ffi::*;
7373
7474
static mut MODULE_DEF: PyModuleDef = PyModuleDef {
7575
m_base: PyModuleDef_HEAD_INIT,
76-
m_name: c_str!("string_sum").as_ptr(),
77-
m_doc: c_str!("A Python module written in Rust.").as_ptr(),
76+
m_name: c"string_sum".as_ptr(),
77+
m_doc: c"A Python module written in Rust.".as_ptr(),
7878
m_size: 0,
7979
m_methods: std::ptr::addr_of_mut!(METHODS).cast(),
8080
m_slots: unsafe { SLOTS as *const [PyModuleDef_Slot] as *mut PyModuleDef_Slot },
@@ -85,12 +85,12 @@ static mut MODULE_DEF: PyModuleDef = PyModuleDef {
8585
8686
static mut METHODS: [PyMethodDef; 2] = [
8787
PyMethodDef {
88-
ml_name: c_str!("sum_as_string").as_ptr(),
88+
ml_name: c"sum_as_string".as_ptr(),
8989
ml_meth: PyMethodDefPointer {
9090
PyCFunctionFast: sum_as_string,
9191
},
9292
ml_flags: METH_FASTCALL,
93-
ml_doc: c_str!("returns the sum of two integers as a string").as_ptr(),
93+
ml_doc: c"returns the sum of two integers as a string".as_ptr(),
9494
},
9595
// A zeroed PyMethodDef to mark the end of the array.
9696
PyMethodDef::zeroed(),
@@ -178,7 +178,7 @@ pub unsafe extern "C" fn sum_as_string(
178178
if nargs != 2 {
179179
PyErr_SetString(
180180
PyExc_TypeError,
181-
c_str!("sum_as_string expected 2 positional arguments").as_ptr(),
181+
c"sum_as_string expected 2 positional arguments".as_ptr(),
182182
);
183183
return std::ptr::null_mut();
184184
}
@@ -202,7 +202,7 @@ pub unsafe extern "C" fn sum_as_string(
202202
None => {
203203
PyErr_SetString(
204204
PyExc_OverflowError,
205-
c_str!("arguments too large to add").as_ptr(),
205+
c"arguments too large to add".as_ptr(),
206206
);
207207
std::ptr::null_mut()
208208
}

0 commit comments

Comments
 (0)