Python is live language

by Mukhammad Karimov


Posted on Sun 09 December 2018



Introduction

I have been programming in Python for a while and have been familiar with differences between compiled vs interpreted languages.

However, I recently learned many Python features that make the language fundamentally different from others.

Example

Here is a simple well-known hello function. We can call it just like the same way in other programming languages.

def hello(name="World"):
    s = f"Hello {name}!"
    print(s)


hello("Mukhammad")      # Hello Mukhammad!
hello()                 # Hello World!

And more

But it's more than that. Functions are first-class objects in Python. It took me for a quite a bit of time to truly comprehend what that means. What it applies are:

We can assign a function to a variable and call it.

print(hello)            # <function hello at 0x10f56fe18>
hello2 = hello
print(hello2)           # <function hello at 0x10f56fe18>
hello2 is hello         # True
hello2()                # Hello World!

We can give a function as an argument to another function.

def stars(func):
    print("****", func("Jimmy"), "****")

stars(hello)            # **** Hello Jimmy! ****

Again functions are objects they know more than we think of:

print(hello.__name__)               # hello
print(hello.__module__)             # __main__    
print(hello.__defaults__)           # ('World',)
print(hello.__dict__)               # {}
print(hello.__code__)               # <code object hello at 0x10d140540, file "hello.py", line 1>
print(hello.__code__.co_code)       # b'd\x01|\x00\x9b\x00d\x02\x9d\x03S\x00'
print(hello.__code__.co_nlocals)    # 1
print(hello.__code__.co_varnames)   # ('name',)

and so on. Official documentation has Data model chapter to explain all.

We can go further and inspect objects:

from inspect import getsource, getfile, signature

print(getsource(hello))     # def hello(name="World"):\n    return f"Hello {name}!"\n
print(getfile(hello))       # hello.py
print(signature(hello))     # (name='World')

Conclusion

Python is a powerful, dynamic, friendly language to learn. It has unique features that worth mastering. They made the language different from contemporary ones. For developers, knowing them makes an expert so that we can build awesome stuff on top of them.

Happy Pythoning!


About me
Generic placeholder image

Mukhammad Karimov

I'm a Software Developer at Super Dispatch (TechStars '16). First graduate of Inha University in Tashkent, young prominent blogger, and pythonista. I write about programming, life hacks, and sometimes travel experience.

Categories