Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Remove unnecessary np.{,as}array / astype calls. #24295

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 29, 2022
Merged

Conversation

anntzer
Copy link
Contributor

@anntzer anntzer commented Oct 28, 2022

Quite often numpy will call asarray for us, saving us the need to call asarray explicitly.

When we do call asarray (or array) ourselves, a dtype can directly be passed in, rather than immediately calling astype immediately after. Passing the dtype makes it unnecessary for asarray to infer the dtype of the passed-in container, and can also save an extra array allocation if asarray first has to allocate an array of a type and astype immediately has to allocate an array of another type.

PR Summary

PR Checklist

Tests and Styling

  • Has pytest style unit tests (and pytest passes).
  • Is Flake 8 compliant (install flake8-docstrings and run flake8 --docstring-convention=all).

Documentation

  • Documentation is sphinx and numpydoc compliant (the docs should build without error).
  • New plotting related features are documented with examples.

Release Notes

  • New features are marked with a .. versionadded:: directive in the docstring and documented in doc/users/next_whats_new/
  • API changes are marked with a .. versionchanged:: directive in the docstring and documented in doc/api/next_api_changes/
  • Release notes conform with instructions in next_whats_new/README.rst or next_api_changes/README.rst

@@ -696,7 +696,7 @@ def test_pathcollection_legend_elements():

h, l = sc.legend_elements(fmt="{x:g}")
assert len(h) == 5
assert_array_equal(np.array(l).astype(float), np.arange(5))
assert_array_equal(l, ["0", "1", "2", "3", "4"])
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this a list of str? Can it be a regular assert?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indeed; switched more places to use plain asserts.

@@ -727,7 +727,7 @@ def test_pathcollection_legend_elements():

levels = [-1, 0, 55.4, 260]
h6, lab6 = sc.legend_elements(num=levels, prop="sizes", fmt="{x:g}")
assert_array_equal(np.array(lab6).astype(float), levels[2:])
assert_array_equal(np.asarray(lab6, float), levels[2:])
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How come this one became np.asarray when the above one remained np.array?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Switched to a plain assert, as above.

@@ -67,7 +67,7 @@ def test_sankey2():
s = Sankey(flows=[0.25, -0.25, 0.5, -0.5], labels=['Foo'],
orientations=[-1], unit='Bar')
sf = s.finish()
assert np.all(np.equal(np.array((0.25, -0.25, 0.5, -0.5)), sf[0].flows))
assert np.array_equal(sf[0].flows, [0.25, -0.25, 0.5, -0.5])
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Better to use numpy.testing.assert_array_equal() because that gives better error messages. I wouldn’t bother to go through all tests and change it, but if you rewrite something, that’s the way to go.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, fixed.

@@ -1464,7 +1464,7 @@ def on_pick(event):
line = event.artist
xdata, ydata = line.get_data()
ind = event.ind
print('on pick line:', np.array([xdata[ind], ydata[ind]]).T)
print('on pick line:', xdata[ind], ydata[ind])
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I bet this array call was here to get reasonably truncated repr:

Suggested change
print('on pick line:', xdata[ind], ydata[ind])
print(f'on pick line: {ind}: ({xdata[ind]:.3f}, {ydata[ind]:.3f})')

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fair enough, fixed.

Copy link
Member

@tacaswell tacaswell left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

modulo my comment about formatting in the docstring line.

@tacaswell tacaswell added this to the v3.7.0 milestone Oct 29, 2022
Copy link
Member

@timhoffm timhoffm left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Modulo @tacaswell’s comment and the flake8 unused import.

Quite often numpy will call asarray for us, saving us the need to call
asarray explicitly.

When we do call asarray (or array) ourselves, a dtype can directly be
passed in, rather than immediately calling astype immediately after.
Passing the dtype makes it unnecessary for asarray to infer the dtype
of the passed-in container, and can also save an extra array allocation
if asarray first has to allocate an array of a type and astype
immediately has to allocate an array of another type.
@anntzer
Copy link
Contributor Author

anntzer commented Oct 29, 2022

Done.

@tacaswell
Copy link
Member

Can self-merge on green.

@timhoffm timhoffm merged commit c8d1656 into matplotlib:main Oct 29, 2022
@anntzer anntzer deleted the ua branch October 29, 2022 22:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants