Kalcifer
Kalcifer

Reputation: 1600

Can you perform an inline import in Python?

Say you only wanted to call a regular expression a single time in you code. As far as I am aware, this means that you then need to do import re somewhere before your call of a function from re. Is it possible to combine this with the function call, in-line? I thought maybe something like this would work

print(import re; re.search(r'<regex>', <string>).group())

but it just threw an error saying invalid syntax at the point of the import. This leads me to believe that the only way to do this is

import re
print(re.search(r'<regex>'), <string>).group())

Upvotes: 2

Views: 3401

Answers (2)

superqwerty
superqwerty

Reputation: 308

E.g. Use like this:

python -c 'import cyrtranslit; print(cyrtranslit.to_latin("бла-бла-бла", "ru"))'

Or like this:

python -c 'import cyrtranslit,sys; print(cyrtranslit.to_latin(sys.argv[1], "ru"))' 'бла-бла-бла'

Result: bla-bla-bla

Or like this:

python -c 'import sys; from urllib import parse; print(parse.unquote(sys.argv[1]))' 'bla%20bla%20bla'

Result: bla bla bla

Upvotes: 1

Red
Red

Reputation: 27557

Answering the question:

Can You Perform an Inline Import in Python?

You can use the built-in importlib module:

print(importlib.import_module('re').search("h", "hello").group())

Output:

'h'

Of course, it would require you to import the importlib module first:

import importlib

print(importlib.import_module('re').search("h", "hello").group())

From the documentation:

The import_module() function acts as a simplifying wrapper around importlib.__import__(). This means all semantics of the function are derived from importlib.__import__(). The most important difference between these two functions is that import_module() returns the specified package or module (e.g. pkg.mod), while __import__() returns the top-level package or module (e.g. pkg).

Upvotes: 1

Related Questions