static_typing.rst 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. .. _doc_gdscript_static_typing:
  2. Static typing in GDScript
  3. =========================
  4. In this guide, you will learn:
  5. - how to use static typing in GDScript;
  6. - that static types can help you avoid bugs;
  7. - that static typing improves your experience with the editor.
  8. Where and how you use this language feature is entirely up to you: you can use it
  9. only in some sensitive GDScript files, use it everywhere, or don't use it at all.
  10. Static types can be used on variables, constants, functions, parameters,
  11. and return types.
  12. A brief look at static typing
  13. -----------------------------
  14. With static typing, GDScript can detect more errors without even running the code.
  15. Also type hints give you and your teammates more information as you're working,
  16. as the arguments' types show up when you call a method. Static typing improves
  17. editor autocompletion and :ref:`documentation <doc_gdscript_documentation_comments>`
  18. of your scripts.
  19. Imagine you're programming an inventory system. You code an ``Item`` class,
  20. then an ``Inventory``. To add items to the inventory, the people who work with
  21. your code should always pass an ``Item`` to the ``Inventory.add()`` method.
  22. With types, you can enforce this::
  23. class_name Inventory
  24. func add(reference: Item, amount: int = 1):
  25. var item := find_item(reference)
  26. if not item:
  27. item = _instance_item_from_db(reference)
  28. item.amount += amount
  29. Static types also give you better code completion options. Below, you can see
  30. the difference between a dynamic and a static typed completion options.
  31. You've probably encountered a lack of autocomplete suggestions after a dot:
  32. .. figure:: img/typed_gdscript_code_completion_dynamic.webp
  33. :alt: Completion options for dynamic typed code.
  34. This is due to dynamic code. Godot cannot know what value type you're passing
  35. to the function. If you write the type explicitly however, you will get all
  36. methods, properties, constants, etc. from the value:
  37. .. figure:: img/typed_gdscript_code_completion_typed.webp
  38. :alt: Completion options for static typed code.
  39. .. tip::
  40. If you prefer static typing, we recommend enabling the
  41. **Text Editor > Completion > Add Type Hints** editor setting. Also consider
  42. enabling `some warnings <Warning system_>`_ that are disabled by default.
  43. .. UPDATE: Planned feature. If JIT/AOT are implemented, update this paragraph.
  44. Also, typed GDScript improves performance by using optimized opcodes when operand/argument
  45. types are known at compile time. More GDScript optimizations are planned in the future,
  46. such as JIT/AOT compilation.
  47. Overall, typed programming gives you a more structured experience. It
  48. helps prevent errors and improves the self-documenting aspect of your
  49. scripts. This is especially helpful when you're working in a team or on
  50. a long-term project: studies have shown that developers spend most of
  51. their time reading other people's code, or scripts they wrote in the
  52. past and forgot about. The clearer and the more structured the code, the
  53. faster it is to understand, the faster you can move forward.
  54. How to use static typing
  55. ------------------------
  56. To define the type of a variable, parameter, or constant, write a colon after the name,
  57. followed by its type. E.g. ``var health: int``. This forces the variable's type
  58. to always stay the same::
  59. var damage: float = 10.5
  60. const MOVE_SPEED: float = 50.0
  61. func sum(a: float = 0.0, b: float = 0.0) -> float:
  62. return a + b
  63. Godot will try to infer types if you write a colon, but you omit the type::
  64. var damage := 10.5
  65. const MOVE_SPEED := 50.0
  66. func sum(a := 0.0, b := 0.0) -> float:
  67. return a + b
  68. .. note::
  69. 1. There is no difference between ``=`` and ``:=`` for constants.
  70. 2. You don't need to write type hints for constants, as Godot sets it automatically
  71. from the assigned value. But you can still do so to make the intent of your code clearer.
  72. Also, this is useful for typed arrays (like ``const A: Array[int] = [1, 2, 3]``),
  73. since untyped arrays are used by default.
  74. What can be a type hint
  75. ~~~~~~~~~~~~~~~~~~~~~~~
  76. Here is a complete list of what can be used as a type hint:
  77. 1. ``Variant``. Any type. In most cases this is not much different from an untyped
  78. declaration, but increases readability. As a return type, forces the function
  79. to explicitly return some value.
  80. 2. *(Only return type)* ``void``. Indicates that the function does not return any value.
  81. 3. :ref:`Built-in types <doc_gdscript_builtin_types>`.
  82. 4. Native classes (``Object``, ``Node``, ``Area2D``, ``Camera2D``, etc.).
  83. 5. :ref:`Global classes <doc_gdscript_basics_class_name>`.
  84. 6. :ref:`Inner classes <doc_gdscript_basics_inner_classes>`.
  85. 7. Global, native and custom named enums. Note that an enum type is just an ``int``,
  86. there is no guarantee that the value belongs to the set of enum values.
  87. 8. Constants (including local ones) if they contain a preloaded class or enum.
  88. You can use any class, including your custom classes, as types. There are two ways
  89. to use them in scripts. The first method is to preload the script you want to use
  90. as a type in a constant::
  91. const Rifle = preload("res://player/weapons/rifle.gd")
  92. var my_rifle: Rifle
  93. The second method is to use the ``class_name`` keyword when you create.
  94. For the example above, your ``rifle.gd`` would look like this::
  95. class_name Rifle
  96. extends Node2D
  97. If you use ``class_name``, Godot registers the ``Rifle`` type globally in the editor,
  98. and you can use it anywhere, without having to preload it into a constant::
  99. var my_rifle: Rifle
  100. Specify the return type of a function with the arrow ``->``
  101. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  102. To define the return type of a function, write a dash and a right angle bracket ``->``
  103. after its declaration, followed by the return type::
  104. func _process(delta: float) -> void:
  105. pass
  106. The type ``void`` means the function does not return anything. You can use any type,
  107. as with variables::
  108. func hit(damage: float) -> bool:
  109. health_points -= damage
  110. return health_points <= 0
  111. You can also use your own classes as return types::
  112. # Adds an item to the inventory and returns it.
  113. func add(reference: Item, amount: int) -> Item:
  114. var item: Item = find_item(reference)
  115. if not item:
  116. item = ItemDatabase.get_instance(reference)
  117. item.amount += amount
  118. return item
  119. Covariance and contravariance
  120. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  121. When inheriting base class methods, you should follow the `Liskov substitution
  122. principle <https://en.wikipedia.org/wiki/Liskov_substitution_principle>`__.
  123. **Covariance:** When you inherit a method, you can specify a return type that is
  124. more specific (**subtype**) than the parent method.
  125. **Contravariance:** When you inherit a method, you can specify a parameter type
  126. that is less specific (**supertype**) than the parent method.
  127. Example::
  128. class_name Parent
  129. func get_property(param: Label) -> Node:
  130. # ...
  131. ::
  132. class_name Child extends Parent
  133. # `Control` is a supertype of `Label`.
  134. # `Node2D` is a subtype of `Node`.
  135. func get_property(param: Control) -> Node2D:
  136. # ...
  137. Specify the element type of an ``Array``
  138. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  139. To define the type of an ``Array``, enclose the type name in ``[]``.
  140. An array's type applies to ``for`` loop variables, as well as some operators like
  141. ``[]``, ``[]=``, and ``+``. Array methods (such as ``push_back``) and other operators
  142. (such as ``==``) are still untyped. Built-in types, native and custom classes,
  143. and enums may be used as element types. Nested array types
  144. (like ``Array[Array[int]]``) are not supported.
  145. ::
  146. var scores: Array[int] = [10, 20, 30]
  147. var vehicles: Array[Node] = [$Car, $Plane]
  148. var items: Array[Item] = [Item.new()]
  149. var array_of_arrays: Array[Array] = [[], []]
  150. # var arrays: Array[Array[int]] -- disallowed
  151. for score in scores:
  152. # score has type `int`
  153. # The following would be errors:
  154. scores += vehicles
  155. var s: String = scores[0]
  156. scores[0] = "lots"
  157. Since Godot 4.2, you can also specify a type for the loop variable in a ``for`` loop.
  158. For instance, you can write::
  159. var names = ["John", "Marta", "Samantha", "Jimmy"]
  160. for name: String in names:
  161. pass
  162. The array will remain untyped, but the ``name`` variable within the ``for`` loop
  163. will always be of ``String`` type.
  164. Type casting
  165. ~~~~~~~~~~~~
  166. Type casting is an important concept in typed languages.
  167. Casting is the conversion of a value from one type to another.
  168. Imagine an ``Enemy`` in your game, that ``extends Area2D``. You want it to collide
  169. with the ``Player``, a ``CharacterBody2D`` with a script called ``PlayerController``
  170. attached to it. You use the ``body_entered`` signal to detect the collision.
  171. With typed code, the body you detect is going to be a generic ``PhysicsBody2D``,
  172. and not your ``PlayerController`` on the ``_on_body_entered`` callback.
  173. You can check if this ``PhysicsBody2D`` is your ``Player`` with the ``as`` keyword,
  174. and using the colon ``:`` again to force the variable to use this type.
  175. This forces the variable to stick to the ``PlayerController`` type::
  176. func _on_body_entered(body: PhysicsBody2D) -> void:
  177. var player := body as PlayerController
  178. if not player:
  179. return
  180. player.damage()
  181. As we're dealing with a custom type, if the ``body`` doesn't extend
  182. ``PlayerController``, the ``player`` variable will be set to ``null``.
  183. We can use this to check if the body is the player or not. We will also
  184. get full autocompletion on the player variable thanks to that cast.
  185. .. note::
  186. The ``as`` keyword silently casts the variable to ``null`` in case of a type
  187. mismatch at runtime, without an error/warning. While this may be convenient
  188. in some cases, it can also lead to bugs. Use the ``as`` keyword only if this
  189. behavior is intended. A safer alternative is to use the ``is`` keyword::
  190. if not (body is PlayerController):
  191. push_error("Bug: body is not PlayerController.")
  192. var player: PlayerController = body
  193. if not player:
  194. return
  195. player.damage()
  196. You can also simplify the code by using the ``is not`` operator::
  197. if body is not PlayerController:
  198. push_error("Bug: body is not PlayerController")
  199. Alternatively, you can use the ``assert()`` statement::
  200. assert(body is PlayerController, "Bug: body is not PlayerController.")
  201. var player: PlayerController = body
  202. if not player:
  203. return
  204. player.damage()
  205. .. note::
  206. If you try to cast with a built-in type and it fails, Godot will throw an error.
  207. .. _doc_gdscript_static_typing_safe_lines:
  208. Safe lines
  209. ^^^^^^^^^^
  210. You can also use casting to ensure safe lines. Safe lines are a tool to tell you
  211. when ambiguous lines of code are type-safe. As you can mix and match typed
  212. and dynamic code, at times, Godot doesn't have enough information to know if
  213. an instruction will trigger an error or not at runtime.
  214. This happens when you get a child node. Let's take a timer for example:
  215. with dynamic code, you can get the node with ``$Timer``. GDScript supports
  216. `duck-typing <https://stackoverflow.com/a/4205163/8125343>`__,
  217. so even if your timer is of type ``Timer``, it is also a ``Node`` and
  218. an ``Object``, two classes it extends. With dynamic GDScript, you also don't
  219. care about the node's type as long as it has the methods you need to call.
  220. You can use casting to tell Godot the type you expect when you get a node:
  221. ``($Timer as Timer)``, ``($Player as CharacterBody2D)``, etc.
  222. Godot will ensure the type works and if so, the line number will turn
  223. green at the left of the script editor.
  224. .. figure:: img/typed_gdscript_safe_unsafe_line.webp
  225. :alt: Unsafe vs Safe Line
  226. Unsafe line (line 7) vs Safe Lines (line 6 and 8)
  227. .. note::
  228. Safe lines do not always mean better or more reliable code. See the note above
  229. about the ``as`` keyword. For example::
  230. @onready var node_1 := $Node1 as Type1 # Safe line.
  231. @onready var node_2: Type2 = $Node2 # Unsafe line.
  232. Even though ``node_2`` declaration is marked as an unsafe line, it is more
  233. reliable than ``node_1`` declaration. Because if you change the node type
  234. in the scene and accidentally forget to change it in the script, the error
  235. will be detected immediately when the scene is loaded. Unlike ``node_1``,
  236. which will be silently cast to ``null`` and the error will be detected later.
  237. .. note::
  238. You can turn off safe lines or change their color in the editor settings.
  239. Typed or dynamic: stick to one style
  240. ------------------------------------
  241. Typed GDScript and dynamic GDScript can coexist in the same project. But
  242. it's recommended to stick to either style for consistency in your codebase,
  243. and for your peers. It's easier for everyone to work together if you follow
  244. the same guidelines, and faster to read and understand other people's code.
  245. Typed code takes a little more writing, but you get the benefits we discussed
  246. above. Here's an example of the same, empty script, in a dynamic style::
  247. extends Node
  248. func _ready():
  249. pass
  250. func _process(delta):
  251. pass
  252. And with static typing::
  253. extends Node
  254. func _ready() -> void:
  255. pass
  256. func _process(delta: float) -> void:
  257. pass
  258. As you can see, you can also use types with the engine's virtual methods.
  259. Signal callbacks, like any methods, can also use types. Here's a ``body_entered``
  260. signal in a dynamic style::
  261. func _on_area_2d_body_entered(body):
  262. pass
  263. And the same callback, with type hints::
  264. func _on_area_entered(area: CollisionObject2D) -> void:
  265. pass
  266. Warning system
  267. --------------
  268. .. note::
  269. Detailed documentation about the GDScript warning system has been moved to
  270. :ref:`doc_gdscript_warning_system`.
  271. Godot gives you warnings about your code as you write it. The engine identifies
  272. sections of your code that may lead to issues at runtime, but lets you decide
  273. whether or not you want to leave the code as it is.
  274. We have a number of warnings aimed specifically at users of typed GDScript.
  275. By default, these warnings are disabled, you can enable them in Project Settings
  276. (**Debug > GDScript**, make sure **Advanced Settings** is enabled).
  277. You can enable the ``UNTYPED_DECLARATION`` warning if you want to always use
  278. static types. Additionally, you can enable the ``INFERRED_DECLARATION`` warning
  279. if you prefer a more readable and reliable, but more verbose syntax.
  280. ``UNSAFE_*`` warnings make unsafe operations more noticeable, than unsafe lines.
  281. Currently, ``UNSAFE_*`` warnings do not cover all cases that unsafe lines cover.
  282. Common unsafe operations and their safe counterparts
  283. ----------------------------------------------------
  284. ``UNSAFE_PROPERTY_ACCESS`` and ``UNSAFE_METHOD_ACCESS`` warnings
  285. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  286. In this example, we aim to set a property and call a method on an object
  287. that has a script attached with ``class_name MyScript`` and that ``extends
  288. Node2D``. If we have a reference to the object as a ``Node2D`` (for instance,
  289. as it was passed to us by the physics system), we can first check if the
  290. property and method exist and then set and call them if they do::
  291. if "some_property" in node_2d:
  292. node_2d.some_property = 20 # Produces UNSAFE_PROPERTY_ACCESS warning.
  293. if node_2d.has_method("some_function"):
  294. node_2d.some_function() # Produces UNSAFE_METHOD_ACCESS warning.
  295. However, this code will produce ``UNSAFE_PROPERTY_ACCESS`` and
  296. ``UNSAFE_METHOD_ACCESS`` warnings as the property and method are not present
  297. in the referenced type - in this case a ``Node2D``. To make these operations
  298. safe, you can first check if the object is of type ``MyScript`` using the
  299. ``is`` keyword and then declare a variable with the type ``MyScript`` on
  300. which you can set its properties and call its methods::
  301. if node_2d is MyScript:
  302. var my_script: MyScript = node_2d
  303. my_script.some_property = 20
  304. my_script.some_function()
  305. Alternatively, you can declare a variable and use the ``as`` operator to try
  306. to cast the object. You'll then want to check whether the cast was successful
  307. by confirming that the variable was assigned::
  308. var my_script := node_2d as MyScript
  309. if my_script != null:
  310. my_script.some_property = 20
  311. my_script.some_function()
  312. ``UNSAFE_CAST`` warning
  313. ~~~~~~~~~~~~~~~~~~~~~~~
  314. In this example, we would like the label connected to an object entering our
  315. collision area to show the area's name. Once the object enters the collision
  316. area, the physics system sends a signal with a ``Node2D`` object, and the most
  317. straightforward (but not statically typed) solution to do what we want could
  318. be achieved like this::
  319. func _on_body_entered(body: Node2D) -> void:
  320. body.label.text = name # Produces UNSAFE_PROPERTY_ACCESS warning.
  321. This piece of code produces an ``UNSAFE_PROPERTY_ACCESS`` warning because
  322. ``label`` is not defined in ``Node2D``. To solve this, we could first check if the
  323. ``label`` property exist and cast it to type ``Label`` before settings its text
  324. property like so::
  325. func _on_body_entered(body: Node2D) -> void:
  326. if "label" in body:
  327. (body.label as Label).text = name # Produces UNSAFE_CAST warning.
  328. However, this produces an ``UNSAFE_CAST`` warning because ``body.label`` is of a
  329. ``Variant`` type. To safely get the property in the type you want, you can use the
  330. ``Object.get()`` method which returns the object as a ``Variant`` value or returns
  331. ``null`` if the property doesn't exist. You can then determine whether the
  332. property contains an object of the right type using the ``is`` keyword, and
  333. finally declare a statically typed variable with the object::
  334. func _on_body_entered(body: Node2D) -> void:
  335. var label_variant: Variant = body.get("label")
  336. if label_variant is Label:
  337. var label: Label = label_variant
  338. label.text = name
  339. Cases where you can't specify types
  340. -----------------------------------
  341. .. UPDATE: Not supported. If nested types are supported, update this section.
  342. To wrap up this introduction, let's mention cases where you can't use type hints.
  343. This will trigger a **syntax error**.
  344. 1. You can't specify the type of individual elements in an array or a dictionary::
  345. var enemies: Array = [$Goblin: Enemy, $Zombie: Enemy]
  346. var character: Dictionary = {
  347. name: String = "Richard",
  348. money: int = 1000,
  349. inventory: Inventory = $Inventory,
  350. }
  351. 2. Nested types are not currently supported::
  352. var teams: Array[Array[Character]] = []
  353. Summary
  354. -------
  355. .. UPDATE: Planned feature. If more optimizations (possibly JIT/AOT?) are
  356. .. implemented, update this paragraph.
  357. Typed GDScript is a powerful tool. It helps you write more structured code,
  358. avoid common errors, and create scalable and reliable systems. Static types
  359. improve GDScript performance and more optimizations are planned for the future.