Python Forum
What colon (:) in Python mean in this case?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
What colon (:) in Python mean in this case?
#1
As shown below, may anyone help to explain what does the x: int and y: int does in the point class? Source code from [here](https://docs.python.org/3/tutorial/contr...statements)

class Point:
    x: int
    y: int

def where_is(point):
    match point:
        case Point(x=0, y=0):
            print("Origin")
        case Point(x=0, y=y):
            print(f"Y={y}")
        case Point(x=x, y=0):
            print(f"X={x}")
        case Point():
            print("Somewhere else")
        case _:
            print("Not a point")
And also how could I run the above code to obtain each case match?

I had tried these

>>> where_is((1,0))
Not a point

>>> where_is((Point))
Not a point
Reply
#2
I honestly have no idea what they are talking about in the link. A dataclass uses colons like that.
from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

x = Point(1, 2)
print(x)
Output:
Point(x=1, y=2)
But the code in the link does not use a dataclass decorator when declaring class Point. The same kind of notation is used by pydantic.
from pydantic import BaseModel

class Point(BaseModel):
    x: int
    y: int

x = Point(x=1, y=2)
print(x)
Output:
x=1 y=2
Making Point a dataclass allows testing the where_is() function like this:
from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

def where_is(point):
    match point:
        case Point(x=0, y=0):
            print("Origin")
        case Point(x=0, y=y):
            print(f"Y={y}")
        case Point(x=x, y=0):
            print(f"X={x}")
        case Point():
            print("Somewhere else")
        case _:
            print("Not a point")

where_is(Point(0, 0))
where_is(Point(0, 2))
where_is(Point(2, 0))
where_is(Point(None, None))
where_is((0, 0))
Output:
Origin Y=2 X=2 Somewhere else Not a point
Reply
#3
(Dec-28-2022, 04:20 AM)Yapwc Wrote: what does the x: int and y: int does in the point class?
These are type hints on the x and y attributes, they are hints that these attributes both expect to receive int's

They are an annotation that specifies the expected type for a variable, a class attribute, or a function parameter or return value.
Type hints are optional and are not enforced by Python but they are useful to static type analysis tools, and aid IDEs with code completion and refactoring.

https://docs.python.org/3/whatsnew/3.5.h...type-hints Wrote:PEP 484 - Type Hints
Function annotation syntax has been a Python feature since version 3.0 (PEP 3107), however the semantics of annotations has been left undefined.

Experience has shown that the majority of function annotation uses were to provide type hints to function parameters and return values. It became evident that it would be beneficial for Python users, if the standard library included the base definitions and tools for type annotations.

PEP 484 introduces a provisional module to provide these standard definitions and tools, along with some conventions for situations where annotations are not available.

For example, here is a simple function whose argument and return type are declared in the annotations:

def greeting(name: str) -> str:
    return 'Hello ' + name
While these annotations are available at runtime through the usual __annotations__ attribute, no automatic type checking happens at runtime. Instead, it is assumed that a separate off-line type checker (e.g. mypy) will be used for on-demand source code analysis.

The type system supports unions, generic types, and a special type named Any which is consistent with (i.e. assignable to and from) all types.

See also
typing module documentation

PEP 484 – Type Hints
PEP written by Guido van Rossum, Jukka Lehtosalo, and Łukasz Langa; implemented by Guido van Rossum.

PEP 483 – The Theory of Type Hints
PEP written by Guido van Rossum
Yapwc likes this post
Reply
#4
I guess it can be type notation for a class variable. Syntactically that is correct. Logically it doesn't make any sense.

So we have our class Point, a singleton that requires we make instances so they can be passed to where_is() to demonstrate how match works.
class Point():
    x: int
    y: int

def where_is(point):
    match point:
        case Point(x=0, y=0):
            print("Origin")
        case Point(x=0, y=y):
            print(f"Y={y}")
        case Point(x=x, y=0):
            print(f"X={x}")
        case Point():
            print("Somewhere else")
        case _:
            print("Not a point")

point = Point()
where_is(point)
Point.x, Point.y = 0, 0
where_is(point)
Point.x, Point.y = 0, 1
where_is(point)
Point.x, Point.y = 1, 0
where_is(point)
where_is((0, 0))
That is just ugly. If the ": int" really is type annotation for class variables, this is a bad example.

It works better, but is longer, if x and y are properties.
class Point():
    def __init__(self, x=None, y=None):
        self._x, self._y = x, y

    @property
    def x(self) -> int:
        return self._x

    @x.setter
    def x(self, value: int):
        self._x = value

    @property
    def y(self) -> int:
        return self._y

    @y.setter
    def y(self, value: int) :
        self._y = value

 
def where_is(point):
    match point:
        case Point(x=0, y=0):
            print("Origin")
        case Point(x=0, y=y):
            print(f"Y={y}")
        case Point(x=x, y=0):
            print(f"X={x}")
        case Point():
            print("Somewhere else")
        case _:
            print("Not a point")
 
where_is(Point(0, 0))
where_is(Point(0, 1))
where_is(Point(1, 0))
where_is(Point())
where_is((0, 0))
Reply
#5
There is a mistake in the tutorial,they have copy from PEP636 but forget the @dataclass .
So there see it's like this.
from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

def where_is(point):
    match point:
        case Point(x=0, y=0):
            print("Origin")
        case Point(x=0, y=y):
            print(f"Y={y}")
        case Point(x=x, y=0):
            print(f"X={x}")
        case Point():
            print("Somewhere else")
        case _:
            print("Not a point")
Then it work as it should.
>>> point = Point(0, 0)
>>> where_is(point)
Origin
>>> 
>>> point = Point(0, 9)
>>> where_is(point)
Y=9
>>> 
>>> point = Point(4, 0)
>>> where_is(point)
X=4
>>> 
>>> point = Point('hello', 'world')
>>> where_is(point)
Somewhere else
Yapwc likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  remove colon if value is None wardancer84 7 1,943 Feb-02-2022, 02:32 PM
Last Post: ibreeden
  Switch case or match case? Frankduc 9 4,553 Jan-20-2022, 01:56 PM
Last Post: Frankduc
  Logstash - sending Logstash messages to another host in case of Failover in python Suriya 0 1,682 Jul-27-2021, 02:02 PM
Last Post: Suriya
  Help: write 'case' with Python ICanIBB 2 1,882 Jan-27-2021, 09:39 PM
Last Post: Larz60+
  How to use switch/case in python? newbieguy 9 4,106 Nov-08-2019, 11:35 AM
Last Post: newbieguy
  How to write switch case statement in Python pyhelp 9 9,256 Nov-11-2018, 08:53 PM
Last Post: woooee
  Is there a something like "case" in Python 3.6? Raptor88 18 20,907 Feb-27-2017, 02:44 AM
Last Post: Raptor88

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020