72

I'm a programming student and my teacher is starting with C to teach us the programming paradigms, he said it's ok if I deliver my homework in python (it's easier and faster for the homeworks). And I would like to have my code to be as close as possible as in plain C.
Question is:
How do I declare data types for variables in python like you do in C. ex:

int X,Y,Z;

I know I can do this in python:

x = 0
y = 0
z = 0

But that seems a lot of work and it misses the point of python being easier/faster than C. So, whats the shortest way to do this?
P.S. I know you don't have to declare the data type in python most of the time, but still I would like to do it so my code looks as much possible like classmates'.

Jagoda Gorus
  • 329
  • 4
  • 18
Guillermo Siliceo Trueba
  • 4,251
  • 5
  • 34
  • 47
  • 4
    You're not quite understanding what variables are in Python. Think of it like C void* pointers: they don't have an inherent type, they are names used to refer to, well, anything. In Python, objects exist out there in the interpreter's memory jungle, and you can give them names and remember where to find them using variables. Your variable doesn't have a type in the C sense, it just points to an object. – salezica Oct 15 '10 at 00:35

8 Answers8

175

Starting with Python 3.6, you can declare types of variables and functions, like this :

explicit_number: type

or for a function

def function(explicit_number: type) -> type:
    pass

This example from this post: How to Use Static Type Checking in Python 3.6 is more explicit

from typing import Dict
    
def get_first_name(full_name: str) -> str:
    return full_name.split(" ")[0]

fallback_name: Dict[str, str] = {
    "first_name": "UserFirstName",
    "last_name": "UserLastName"
}

raw_name: str = input("Please enter your name: ")
first_name: str = get_first_name(raw_name)

# If the user didn't type anything in, use the fallback name
if not first_name:
    first_name = get_first_name(fallback_name)

print(f"Hi, {first_name}!")

See the docs for the typing module

Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
Cam T
  • 1,965
  • 2
  • 8
  • 8
  • 8
    Finally a proper answer to the question.... But even this cannot avoid assigning an incompatible values to vars. Only that IDEs like pycharm can use the info to find possible errors... – wmac Feb 01 '19 at 12:52
  • 2
    @wmac This is merely a type hint to developers. Indeed, smart IDEs can parse this and warn you about mismatches, but that's the most they can do. Given Python's dynamic nature, it's acceptable behavior. – Timor Gruber Apr 26 '20 at 16:11
  • Thank you for it still an info / hint purposes only – swdev May 28 '20 at 00:35
  • So in java for eg when a variable type is defined, it does not allow assigning an incompatible type. But python still does. So does it really help? – sjd Jun 05 '20 at 08:14
  • @wmac If you need to validate data objects you can do it with dataclasses https://docs.python.org/3/library/dataclasses.html, but because the duck typing of python ithe variables are dynamic can mutate so the interprete don't check the static types, but it help a lot for documenting and develope knowing what the variable is. – Cam T Nov 26 '20 at 20:12
27

Edit: Python 3.5 introduced type hints which introduced a way to specify the type of a variable. This answer was written before this feature became available.

There is no way to declare variables in Python, since neither "declaration" nor "variables" in the C sense exist. This will bind the three names to the same object:

x = y = z = 0
mousetail
  • 7,009
  • 4
  • 25
  • 45
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
13

Simply said: Typing in python is useful for hinting only.

x: int = 0
y: int = 0 
z: int = 0
12

Python isn't necessarily easier/faster than C, though it's possible that it's simpler ;)

To clarify another statement you made, "you don't have to declare the data type" - it should be restated that you can't declare the data type. When you assign a value to a variable, the type of the value becomes the type of the variable. It's a subtle difference, but different nonetheless.

KevinDTimm
  • 14,226
  • 3
  • 42
  • 60
  • I would say that C is simpler than python. It lacks decorators, metaclasses, descriptors, etc. Granted, those can all be implemented in C but then it's your program that's sophisticated and not the underlaying language. – aaronasterling Oct 14 '10 at 13:09
  • @aaron - note I said possible :) I've done C for more than 25 years and python for only a year - I still write all my little stuff in C (but not because it's simple) – KevinDTimm Oct 14 '10 at 13:11
  • The language might be simpler in terms of functions. But the point is it's NOT simpler to implement decorators, metaclasses, descriptors, etc – Falmarri Oct 14 '10 at 20:52
  • 6
    C is a fairly simple language. That definitely doesn't mean that writing code in C is simple. :) – Nate C-K Jan 20 '11 at 04:29
  • These days, you can use [type hinting](https://docs.python.org/library/typing.html) to declare a data type, it's not used at run time though. – Boris Verkhovskiy Sep 06 '19 at 23:01
11

I'm surprised no one has pointed out that you actually can do this:

decimalTwenty = float(20)

In a lot of cases it is meaningless to type a variable, as it can be retyped at any time. However in the above example it could be useful. There are other type functions like this such as: int(), long(), float() and complex()

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
DisplayName
  • 239
  • 3
  • 7
  • 5
    I am surprised you say that. Because that does not make your variable typed and that is no different than assigning a value of 20.0... none of them makes your variable an always float. You can still assign any value to that variable. – wmac Feb 01 '19 at 12:48
5

But strong types and variable definitions are actually there to make development easier. If you haven't thought these things through in advance you're not designing and developing code but merely hacking.

Loose types simply shift the complexity from "design/hack" time to run time.

4

Everything in Python is an object, and that includes classes, class instances, code in functions, libraries of functions called modules, as well as data values like integers, floating-point numbers, strings, or containers like lists and dictionaries. It even includes namespaces which are dictionary-like (or mapping) containers which are used to keep track of the associations between identifier names (character string objects) and to the objects which currently exist. An object can even have multiple names if two or more identifiers become associated with the same object.

Associating an identifier with an object is called "binding a name to the object". That's the closest thing to a variable declaration there is in Python. Names can be associated with different objects at different times, so it makes no sense to declare what type of data you're going to attach one to -- you just do it. Often it's done in one line or block of code which specifies both the name and a definition of the object's value causing it to be created, like <variable> = 0 or a function starting with a def <funcname>.

How this helps.

martineau
  • 119,623
  • 25
  • 170
  • 301
0

I use data types to assert unique values in python 2 and 3. Otherwise I cant make them work like a str or int types. However if you need to check a value that can have any type except a specific one, then they are mighty useful and make code read better.

Inherit object will make a type in python.

class unset(object):
    pass
>>> print type(unset)
<type 'type'>

Example Use: you might want to conditionally filter or print a value using a condition or a function handler so using a type as a default value will be useful.

from __future__ import print_function # make python2/3 compatible
class unset(object):
    pass


def some_func(a,b, show_if=unset):
    result = a + b
    
    ## just return it
    if show_if is unset:
        return result
    
    ## handle show_if to conditionally output something
    if hasattr(show_if,'__call__'):
        if show_if(result):
            print( "show_if %s = %s" % ( show_if.__name__ , result ))
    elif show_if:
        print(show_if, " condition met ", result)
        
    return result
    
print("Are > 5)")
for i in range(10):
    result = some_func(i,2, show_if= i>5 )
    
def is_even(val):
    return not val % 2


print("Are even")
for i in range(10):
    result = some_func(i,2, show_if= is_even )

Output

Are > 5)
True  condition met  8
True  condition met  9
True  condition met  10
True  condition met  11
Are even
show_if is_even = 2
show_if is_even = 4
show_if is_even = 6
show_if is_even = 8
show_if is_even = 10

if show_if=unset is perfect use case for this because its safer and reads well. I have also used them in enums which are not really a thing in python.

Peter Moore
  • 1,632
  • 1
  • 17
  • 31