Skip to content

Commit a404be7

Browse files
committed
Avoid unnecessary copies in snippets for file upload
Prior to this commit, we recommended extracting a string representation of the uploaded file with: uploaded_file.tobytes().decode("utf-8") This causes a copy of the memoryview to be created when it's converted to bytes. This copy is immediately discarded when it is decoded. Switching to: codecs.decode(uploaded_file, encoding="utf-8") means that we apparently don't create the intermediate copy. This commit also adds an example of using the uploaded file in an image widget.
1 parent c54974e commit a404be7

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

docs/source/examples/Widget List.ipynb

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1069,10 +1069,11 @@
10691069
"#=> b'This is the content of example.txt.\\n'\n",
10701070
"```\n",
10711071
"\n",
1072-
"To get the contents as a string:\n",
1072+
"You can get the contents as a string if the file is a text file (more precisely, if the file can be decoded as UTF-8):\n",
10731073
"\n",
10741074
"```python\n",
1075-
"uploaded_file[\"content\"].tobytes().decode(\"utf-8\")\n",
1075+
"import codecs\n",
1076+
"codecs.decode(uploaded_file[\"content\"], encoding=\"utf-8\")\n",
10761077
"#=> 'This is the content of example.txt.\\n'\n",
10771078
"```\n",
10781079
"\n",
@@ -1086,7 +1087,15 @@
10861087
"To convert the uploaded file into a Pandas dataframe, you need to convert it to a StringIO object:\n",
10871088
"\n",
10881089
"```python\n",
1089-
"pd.read_csv(io.StringIO(uploaded_file[\"content\"].tobytes().decode(\"utf-8\")))\n",
1090+
"import io\n",
1091+
"import pandas as pd\n",
1092+
"pd.read_csv(io.StringIO(codecs.decode(uploaded_file[\"content\"], encoding=\"utf-8\")))\n",
1093+
"```\n",
1094+
"\n",
1095+
"If the uploaded file is an image, you can visualize it with an image widget:\n",
1096+
"\n",
1097+
"```python\n",
1098+
"widgets.Image(value=uploaded_file[\"content\"].tobytes())\n",
10901099
"```\n",
10911100
"\n",
10921101
"<div class=\"alert alert-info\">\n",

0 commit comments

Comments
 (0)