-2

I'm new to Python programming and I've noticed that when using the 'matplotlib' library there is a ton of redundant calls when creating a visual plot. In other languages, you can use the "with" statement to reduce calls to the object and or statement. I get errors whenever I attempt it using those language's syntax (VBA/*.NET). Is there an equivalent way to do the reduce the calls to the "plt" statement? From the documentation, "with" in Python only appears to apply to objects, but is there another that would work on statements?

Example of what I'm looking for:

with plt
    .xlabel("Time")
    .ylabel("Amplitude")
end with
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • cant edit because there are too many edits on stack rn. for the code sample provided there is supposed to be a new line/enter click after each callout – turkeybozwe Feb 21 '23 at 18:47
  • No but if its your own object you could make `xlabel` return self to chain functions, that wouldn't really be too pythonic though – Sayse Feb 21 '23 at 18:48
  • 3
    No, Python does not have a similar syntactic construct. – chepner Feb 21 '23 at 18:48
  • 2
    The actual Python `with` statement does something *completely* different. – chepner Feb 21 '23 at 18:50
  • Python has never caved in to constructs that do nothing but reduce typing. It doesn't really save all that much, and it can cause ambiguities when they are nested. – Tim Roberts Feb 21 '23 at 18:51
  • Perhaps inadvisable, but the easiest solution for a small thing would be `from plt.pyplot import *`, which would let you call `xlabel()` without the plt prefix. That does mean you need to be careful not to shadow those functions (eg doing `xlabel = "example label"; xlabel(xlabel)` will cause errors. – Kaia Feb 21 '23 at 18:53
  • Similarly, `import matplotlib.pyplot as plt` could be shortened to `as pt` or `p` if you *really* hate the extra 3 chararacters. But `plt` is reasonably standard and I'd stick with that. – Kaia Feb 21 '23 at 18:55
  • Thank you all for the feedback; I'll follow your advice @kaia and keep it as plt. – turkeybozwe Feb 21 '23 at 19:01
  • And please remember PEP 8, the [Style Guide for Python Code](https://peps.python.org/pep-0008/): "Wildcard imports (`from import *`) should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools." – Matthias Feb 21 '23 at 19:26

2 Answers2

1

No, there is nothing remotely like this in Python. The description "'with' in Python only appears to apply to objects" does not make any sense at all, but it is true that Python's with is completely unrelated to this with from other languages.

If you want to avoid redundant typing, consider aliasing the result of a calculation:

# before
# x.y.z = 1
# x.y.w = 2
# after
v = x.y
v.z = 1
v.w = 2

or using a function to wrap up multiple related steps:

# before
x.y = 1
x.z = 2
w.y = 1
w.z = 2
# after
def modify(t):
    t.y = 1
    t.z = 2
modify(x)
modify(w)
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
0

The closest thing you can do to avoid writing plt many times is using a list of methods names, arguments, grab the appropriate method with getattr and pass the arguments to it:

for method, arg in (("xlabel", "Time"),
                    ("ylabel", "Amplitude")):
    getattr(plt, method)(arg)

It's not advisable to turn a simple code into such a thing, especially when the methods and arguments do not need to be dynamic at all.

Guimoute
  • 4,407
  • 3
  • 12
  • 28
  • 1
    I don't think this relates to the usage pattern OP has in mind. – Karl Knechtel Feb 21 '23 at 18:52
  • 1
    Thanks this is great out of the box thinking for encapsulation, but my intent was just to make it easier faster for the next guy to comprehend/pickup – turkeybozwe Feb 21 '23 at 19:08
  • @turkeybozwe Oh, if you want the next guy to understand what you did, definitely stick to `plt.xlabel("Time")` `plt.ylabel("Amplitude")`. I would also favour the object-oriented approach `ax.set_xlabel`. – Guimoute Feb 22 '23 at 00:19