0

I'm doing this in Maya, but the core issue is from Python. It all boils down to why or doesn't work in this case :

>>> a = ["something",]
>>> b = a[1] or "empty"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

More details:

I need a file's name without the path and extension, and do actions with that in a variable.
So I thought I could just do name = basenamde(cmds.file(q=True, sn-True).split(".")[-2] or []

But when doing it in an empty unsaved scene (which returns nothing when asked the file name it doesn't have), it returns that error. I know I could just declare the variable empty first, then check if the file name exists before assigning it to the variable, but it doesn't sound "elegant" to me. I love short one-liners.

I also have seen this answer that encourages doing this:

b, = a[1] or "empty"

Which I would love to use here, but it doesn't seem to work in Maya 2018 (Python 2.7) with the same error list index out of range.

L0Lock
  • 147
  • 13
  • 2
    when `a` is `[]`, `a[1]` will definitely give `IndexError: list index out of range` even `a[0]` will give the same error. – Talha Tayyab May 08 '23 at 17:26
  • Sure, but why it can't b return "empty" then ? – L0Lock May 08 '23 at 18:11
  • 1
    Because the `or` is never evaluated, the exception has already occurred. `a[4:5]` will return an empty list rather than raising an exception, which is why the answer you linked works. – Jasmijn May 08 '23 at 18:26
  • I thought `or` could be used for that precisely... So I guess I don't have much choice. I tried the other method exactly as in the answer in Maya (py 2.7) but it returns an invalid syntax on `:` from `[4:5]` – L0Lock May 08 '23 at 21:47
  • it works on python 3.10 standalone – L0Lock May 08 '23 at 21:47
  • The error message comes from not being able to access the [1] postion in list a. However, a workaround can be: a = ["something",] try: b = a[1] except: b = "empty" print(b) – Samia Ashraf May 09 '23 at 07:25
  • `or` is working *perfectly fine* in this case. `a[1]` is evaluated first, and that throws the error. – juanpa.arrivillaga May 09 '23 at 18:04

0 Answers0