[Tutor] library terminology and importing
Martin A. Brown
martin at linux-ip.net
Sun Feb 21 21:40:19 EST 2016
I'm inverting the order of your questions, because I think the order of the
answers may help.
>But if I import all of os and datetime, I can use those functions by
>writing the full 'path' 3 levels deep:
[... hold onto your hat, we'll get to datetime.datetime ...]
>from os.path import join,expanduser
>Also, is there proper terminology for each of the 3 sections of
>os.path.expanduser('~') for example? Such as
Yes, there most certainly is; it's good that you are asking. See below.
>os - library (or module?)
>path - ?
>expanduser - function
Here's how you could figure out what they are called. Use 'type' to figure
>>> import os
Observe that the type of os.path.expanduser is function.
It is for this reason that you can importi (and use) the expanduser
function by itself. It can stand alone:
>>> from os.path import expanduser
Side note, for diagnostics, 'type' can be handy, also, for things
>I often use now() and strftime() from datetime, but it seems like I can't
>import just those functions. The os module allows me to import like this:
Ok, so back to datetime...
This should not surpise you. So, datetime is a module. Good.
Oh-ho! What is this one? It's called 'type'? Well, it's a Python
class. You can see it in the source code, if you look for the class
definition of 'datetime' in the module 'datetime'. I find mine in
/usr/lib64/python3.4/datetime.py around line 1290ff. Look for this:
"""datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])
Why am I pointing you to this? Well, in particular, you should see the
following a few lines later (lines 1394 ff in my copy):
def now(cls, tz=None):
"Construct a datetime from time.time() and optional time zone info."
t = _time.time()
return cls.fromtimestamp(t, tz)
If you wish, you can go look up the decorator @classmethod and what
it does, but the main point I'm making here is that this is not a
function! It cannot be separated from the datetime class. It is
(in this case) an alternate constructor for a datetime object. And,
'type' will tell you so:
So, even though the name is available to you and callable, when you
import the module datetime, you can't separate the classmethod
called 'now()' from the datetime.datetime class.
>but I get an error if I try
>from datetime.datetime import now, strftime
If you are mostly interested in shortening your import statement, I have seen
people use this sort of technique:
>>> from datetime import datetime as dt
>>> now = dt.now()
Good luck and enjoy,
Martin A. Brown
More information about the Tutor