how to declare variable type, C style in python

PythonCVariables

Python Problem Overview


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

Python Solutions


Solution 1 - Python

Starting with Python 3.6, you can declare types of variables and funtions, 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

Solution 2 - Python

> 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

Solution 3 - Python

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.

Solution 4 - Python

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

Solution 5 - Python

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

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

Solution 6 - Python

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.

Solution 7 - Python

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.

Solution 8 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGuillermo Siliceo TruebaView Question on Stackoverflow
Solution 1 - PythonCam TView Answer on Stackoverflow
Solution 2 - PythonIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 3 - PythonKevinDTimmView Answer on Stackoverflow
Solution 4 - PythonDisplayNameView Answer on Stackoverflow
Solution 5 - PythonPraphan KlairithView Answer on Stackoverflow
Solution 6 - PythonmartineauView Answer on Stackoverflow
Solution 7 - PythonCarl PickeringView Answer on Stackoverflow
Solution 8 - PythonPeter MooreView Answer on Stackoverflow