static_typing.rst 18 KB

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