10 Things I Love About Tech- Python Edition

So since I already complained about what I hate about tech from a diversity and culture perspective, I felt I needed to explain all the things I love about tech and why I wouldn’t want to be anywhere else.

Everyone would expect me to start with databases or virtualization, but I thought I’d keep everyone on their toes and start with my favorite programming language- PYTHON!

1.Timed Pauses, Stops and Waits

Sometimes systems are just too fast for humans.  It’s important to have proper delays between tasks so that people are able to interact or systems are able to respond to each other in the proper amount of time.  This is where the “sleep” command comes in.  Just like in Bash shell, sleep is used to tell a command to wait:

@logged("%b %d %Y - %H:%M:%S")
def add2(x, y):
    time.sleep(2)
    return x + y

The command above translates to “Time to sleep [in seconds] and then proceed with the next command[s].”  This comes in handy as you time out spaces between tasks and is a common command you’ll see in any python program.

2. Context Managers

The ability to write to files or create scripts dynamically is an important one in any programming language.  We write and append to files as needed and this is something we can do with Python using context management.  Simply open a file, write to it and then remember to close it afterwards, (which I didn’t add

>>>file = open(“/var/testfile.txt”,”w”) 
 
>>>file.write(“#Fix File Script”) 
>>>file.write(“mv /var/testfile.txt /usr/mvfile.sh”) 
>>>file.write(“chmod 774 /var/testfile.txt”) 
>>>file.write(“exit”) 
 
>>>file.close()

3.  Generators

As DBAs, we understand the value of a sequence.  We use them all the time in databases and create them with the simple command:

CREATE SEQUENCE emp_seq
 START WITH     1
 INCREMENT BY   1;

In programming languages, often its just as easy and with Python, we’re able to do all kinds of tasks via a function in a sequential manner.  There are distinct requirements to use a generator, but one of them is to use the word yield, as each function call must yield a value of some sort.

>>> def f():
...   print("-- Ready --")
...   yield 1
...   print("-- Set --")
...   yield 2
...   print("-- Go --")
...   yield 3
>>> gen = f()
>>> next(gen)
-- Ready --
1
>>> next(gen)
-- Set --
2
>>> next(gen)
-- Go --
3

Each of the yield values are stored in the object created by this function.  As you can see, this could be a bit cumbersome, so how can we do it in a simpler manner with Python?

4.  Iterators

Another way to perform something sequentially and simply, is to use an iterator.  While the iterator can save us a lot of time by building out from a list-

>>> f = [1, 2, 3]  
>>> iter(f)
<...iterator object at ...>
>>> f.__iter__()

We can save even more time by using a file as an iterator.  Yes, you heard me-  The file is the iterator and at no time does it create a separate object.  Keep in mind, only sequential access with a single thread is allowed here, too.

>>> f = open('/home/python/dbakevlar/file.txt')
>>> f is f.__iter__()
True
5.  Replacing Values
Sometimes what data is shown, isn’t the data you want returned.  This is pretty easy to change in Python and why its such a common language to use.
>>> local = [80031, 80204, 80221] 
>>> "Westminster","Denver","Aurora" = local

>>> Westminster
80031 
>>> Denver
80204
>>> Aurora
80221
6.  Decorator Function
No, this doesn’t mean we all become Martha Stewart, but these are gorgeous functions that make it easy to do a lot with very little.  In Python, decorators are functions (or objects that can be called) that require an input of optional arguments, a function or class, and return a function or class.

 

from inspect import getargspec as gas   

def decorate(fn):
    argspec = gas(fn)
    scd_argname = argspec[0][1]
    def inner(*args, **kwargs):
        special_value = (kwargs[scd_argname] 
                         if scd_argname in kwargs else args[1])
        if special_value == 2:
            print "nada"
        else:
            print "nada happening"
        return fn(*args, **kwargs)
    return inner

@decorate
def nada(a, b, c=3):
    pass

nada(1,2,3)
nada(1,b=2,c=4)
nada(1,3,5)
nada(1,b=6,c=5)
Note that nada can return the correct values depending on the arguments and is as flexible as we need it to be for a given program, wrapping functions inside another function.
7.  Unpacking with a Range
So I’ve decided I’m working with a range of 10, but I’ll have a set to the first value of 10, (which starts with 0, not 1, peeps) and then B can be anywhere in the range:
>>> a, *rest, b = range(10) 
>>> a 
0
>>> b 
9 
>>> rest [1, 2, 3, 4, 5, 6, 7, 8]
We could also just say we have b that’s a value anywhere in our range:
>>> *rest, b = range(10) 
>> rest 
[0, 1, 2, 3, 4, 5, 6, 7, 8] 
>>> b 
9
8. Reversing Any String
Sometimes you just need to reverse what you see.  Now for reversing searches on zipcodes, it’s very valuable to search by reversing the zipcode and index to remove “hot spots” on location searches.  The ability to reverse data easily in Python can ease this:
>>> Geocode = "80031" 

>>> print a[::-1] 

13008
9. Named String Formatting
Formatting of text is quite simple in Python.  There’s not a lot of complicated additions, just give a few parameter names and go!
print("The %(foo)s is %(bar)i." % {'foo': 'answer', 'bar':42})
The answer is always 42… 🙂
10.  Cool Mathematic Functions:
math.gcd(a)
Return the greatest common divisor, (GCD) for the value provided.
math.isfinite(b)
Return TRUE if x is neither an infinity nor a Not a Number, (NaN), otherwise FALSE.  Interesting enough, 0.0 is considered finite.
min(a), max(b)

Just as you would expect, these functions return the min and the max values for what is shown.

There are a lot more ways that make Python my favorite language to teach anyone just coming into programming, but it’s also robust enough to support an enterprise environment, too.

If you’d like to learn more, I really like the tutorials and slides from the following sites:

 

Print Friendly
May 5th, 2017 by

facebook comments:

  • Facebook
  • Google+
  • LinkedIn
  • Twitter