17

Can I import module in Python giving it two or more aliases in one line?

With two lines this works:

from time import process_time as tic
from time import process_time as toc

This doesn't work, but I would want to be able to write something like:

from time import process_time as tic,toc
Danny Lessio
  • 607
  • 5
  • 13
  • 2
    Can you explain why you would ever want to do this? In general it sounds like a fairly bad idea with no upside. Do you have a legitimate use-case? – smci Jul 09 '18 at 02:01
  • @smci I would imagine they're trying to emulate `tic` and `toc` from languages they're more familiar with (matlab, R, etc), where functions with these names exist to measure elapsed time. – cs95 Jul 09 '18 at 04:36
  • @coldspeed: but `tic` and `toc` are different things, they're not the same alias. `tic`: Starts the timer and stores the start time and the message on the stack. `toc` Notes current timer, computes elapsed time since matching call to tic(); when quiet is FALSE, prints associated message and elapsed time. I was worried that the question was phrased much more generally than *"How do I declare multiple aliases to process_time as tic, toc?"* Other people might conclude this was a good and healthy thing to do in general. – smci Jul 09 '18 at 04:53
  • Is this question about a) the general case how and whether to create multiple aliases for an import (definitely a bad idea) or b) just the OP's very specific case of trying to using multiple aliases to make code superficially look like the original R/Matlab for `tic/toc`? (still not a great idea - just learn the Python equivalent already)? – smci Jul 09 '18 at 05:13

2 Answers2

31

You can do that with

from time import process_time as tic, process_time as toc
Francesco
  • 4,052
  • 2
  • 21
  • 29
  • Thanks Francesco, this is what i was asking for. However I think that the two lines solution is the more readable one. – Danny Lessio Apr 07 '16 at 16:34
7

You could do

from time import process_time as tic

toc = tic
Ithilion
  • 150
  • 1
  • 8