94

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'.

2
  • 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. Commented Oct 15, 2010 at 0:35
  • @salezica Obligatory: Facts and myths about Python names and values by Ned Batchelder Commented Dec 24, 2023 at 21:27

8 Answers 8

207

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

Sign up to request clarification or add additional context in comments.

5 Comments

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 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.
Thank you for it still an info / hint purposes only
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?
@wmac If you need to validate data objects you can do it with dataclasses 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.
29

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

1 Comment

This is outdated as of Python 3.5, which allows static typing. See Cam Ts answer.
19

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

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

1 Comment

The type hinting is very useful for access to intellisense in VS Code
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.

5 Comments

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.
@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)
The language might be simpler in terms of functions. But the point is it's NOT simpler to implement decorators, metaclasses, descriptors, etc
C is a fairly simple language. That definitely doesn't mean that writing code in C is simple. :)
These days, you can use type hinting to declare a data type, it's not used at run time though.
10

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()

2 Comments

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.
The point of that function is also not data typing, but rather data conversion. You are actually showing an example of this as you have passed in an integer argument, yet a data type of float is being returned.
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.

Comments

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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.