Mojo Error: 'X' value has no attribute 'Y'
error: 'X' value has no attribute 'Y' means you wrote value.Y, and the type X has no method or field called Y. Common versions are 'List[Int]' value has no attribute 'sort', 'String' value has no attribute 'length' and 'Array[Int, Int(3)]' value has no attribute 'append'. The type in quotes is the key: it tells you what Mojo thinks your value is. For the other errors in this series, see Mojo Errors Explained.
The error message
Section titled “The error message”def main(): var nums: List[Int] = [3, 1, 2] nums.sort() print(nums)sort.mojo:3:9: error: 'List[Int]' value has no attribute 'sort' nums.sort() ~~~~^mojo: error: failed to parse the provided Mojo source moduleAttribute is the word for anything after a dot: a method like .sort() or a field like .name. The message says that a List[Int] doesn’t have one called sort. Unlike Python’s AttributeError, this happens when you build the program, not when that line runs.
What it means
Section titled “What it means”There are three usual reasons:
- The name is wrong. A typo (
u.nmae), or a Python name that Mojo spells differently or doesn’t have. - The value is a different type than you think. For example an
Arraywhere you expected aList, or anOptional[String]where you expected aString. - Your own type doesn’t have it yet. A struct only has the fields and methods you give it, plus what its traits add, such as
.copy()fromCopyable.
Read the type in the quotes first. If it isn’t the type you expected, it’s reason 2. If it is, look the method up for that type in the standard library docs.
How to fix it
Section titled “How to fix it”Fix 1: Use the Mojo way when Python’s method doesn’t exist
Section titled “Fix 1: Use the Mojo way when Python’s method doesn’t exist”Mojo’s List and String look like Python’s, but they’re not the same. Some methods are missing, and some are free functions instead. List has no .sort(); sorting is the built-in sort(...) function:
def main(): var nums: List[Int] = [3, 1, 2] sort(nums) print(nums, len(nums))Output:
[1, 2, 3] 3The ones people hit most, all checked on Mojo 1.2:
| Python | Mojo error | Mojo instead |
|---|---|---|
nums.sort() |
'List[Int]' value has no attribute 'sort' |
sort(nums) |
nums.length, s.length() |
... has no attribute 'length' |
len(nums), s.byte_length() |
nums.remove(2) |
'List[Int]' value has no attribute 'remove' |
find the index, then nums.pop(i) |
s.title(), s.capitalize() |
'String' value has no attribute 'title' |
not in Mojo 1.2; build it from upper() and lower() |
s.isdigit() |
'String' value has no attribute 'isdigit' |
try Int(s) in a try block |
Many other Python names do exist on String: upper, lower, strip, split, find, replace, startswith, endswith, count. And on List: append, pop, insert, extend, clear, reverse. See Mojo Sorting & Searching and Mojo Strings in Depth.
Fix 2: Give the value the type you meant
Section titled “Fix 2: Give the value the type you meant”A bracket literal without a type is a fixed-size Array, and arrays can’t grow:
def main(): var nums = [3, 1, 2] nums.append(4) print(nums)grow.mojo:3:9: error: 'Array[Int, Int(3)]' value has no attribute 'append' nums.append(4) ~~~~^mojo: error: failed to parse the provided Mojo source moduleThe type in the message shows the real problem: nums is an Array, not a List. Say which type you want:
def main(): var nums: List[Int] = [3, 1, 2] nums.append(4) print(nums)Output:
[3, 1, 2, 4]See Mojo Arrays for when a fixed-size Array is the better choice.
Fix 3: Unwrap an Optional first
Section titled “Fix 3: Unwrap an Optional first”An Optional[String] is a box that might hold a String. The box itself has no .upper(), so name.upper() gives 'Optional[String]' value has no attribute 'upper'. Check that there’s a value, then take it out with .value():
def main(): var name: Optional[String] = String("ada") if name: print(name.value().upper())Output:
ADAd.get(key) on a Dict returns an Optional too, so this comes up a lot with dictionaries. See Mojo Optional.
Fix 4: Fix the field name, or add what your struct is missing
Section titled “Fix 4: Fix the field name, or add what your struct is missing”For your own structs, the message has no “did you mean”, so compare the name with the struct’s fields yourself. u.nmae on a struct with var name: String gives 'User' value has no attribute 'nmae'; the fix is u.name.
.copy() is a special case. It isn’t a method you write; your struct gets it from the Copyable trait. Without that trait, a.copy() fails with 'Team' value has no attribute 'copy'. Add the trait in brackets after the struct name:
@fieldwise_initstruct Team(Copyable): var players: List[String]
def main(): var a = Team(["Ada", "Linus"]) var b = a.copy() b.players.append("Grace") print(len(a.players), len(b.players))Output:
2 3b is a full copy, so adding a player to b doesn’t change a. Mojo Common Traits lists what each trait gives a struct, and Mojo Methods shows how to add your own methods.
Where you’ll usually see it
Section titled “Where you’ll usually see it”- Python list and string habits, as in the table in Fix 1.
- A
Listthat’s really anArray, because the variable had no type. Optionalvalues fromd.get(...)or your own functions.- Errors in
except e:. AnErroronly carries its message;'Error' value has no attribute 'line'means you asked for something it doesn’t store. See Mojo Custom Errors to carry more information.
Related errors
Section titled “Related errors”- use of unknown declaration ‘x’: the name before the dot is unknown, not the one after it.
- value of type ‘X’ cannot be implicitly copied: the other error you meet with
Listand structs that aren’tCopyable. len(String/StringSlice)is not supported: what you get after replacings.length()withlen(s).- All Mojo error pages: the full list.
Practice
Section titled “Practice”1. Clean up a word list
Section titled “1. Clean up a word list”Make this program build. It should print the words sorted, then how many there are.
def main(): var words = ["pear", "apple", "fig"] words.append("kiwi") words.sort() print(words, words.length)Hint: there are three problems: the variable’s type, the sort, and the length.
Show solution
def main(): var words: List[String] = ["pear", "apple", "fig"] words.append("kiwi") sort(words) print(words, len(words))Output:
[apple, fig, kiwi, pear] 4List[String] makes words a growable list, so append exists. Sorting uses the sort function, and the length comes from len. Printing a List[String] shows the words without quotes.
- The error means the type in quotes has no method or field with that name.
- Read the type first: an
ArrayorOptionalwhere you expected aListorStringis a common cause. - Some Python methods are missing or different:
sort(xs),len(xs),s.byte_length(). - Unwrap an
Optionalwithif x:and.value()before calling methods on it. .copy()comes from theCopyabletrait; your own fields and methods must be spelled exactly.
Next up: value of type ‘X’ cannot be implicitly copied, the error for var b = a with a list.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Mojo standard library: every type with its methods, so you can check what exists.
- Mojo tips for Python devs: where Python habits and Mojo APIs differ.
- Mojo structs in the manual: fields and methods on your own types.
- Mojo Lists: our lesson with the
Listmethods you’ll use most.