-1

Want to import functions starting with foo_ only, but

# testcases.py
def foo_1():
    do_1()

def foo_2():
    do_2()

def bar_1():
    do_3()

def bar_2():
    do_4()

# main.py
#!/usr/bin/python3

from testcases import foo_*

foo_1()

# test run
qxu@mymac:~/test$ ./main.py 
  File "/Users/qxu/test/./main.py", line 3
    from testcases import foo_*
                          ^
SyntaxError: invalid syntax

More testcases will be added later, and I don't want to change main.py each time a new foo_ function is added into testcases.py.

2 Answers 2

1

That is not possible in python. But you can do the following.

You can put your testcases in different files. Even within a testcases folder. Then put your foo and bar testcases in foo.py and bar.py files inside that folder respectively. Also, you need __init__.py file in your testcases folder. In your main.py you can then import it like this:

from testcases import foo  # ./testcases/foo.py

foo.foo_1()

Or if you want to have only one file then you can import all with * and then check the method names. You can do that with the inspect module.

import testcases
from inspect import getmembers, isfunction

for name, func in getmembers(testcases, isfunction):
    if name.startswith("foo_"):
        func()
Sign up to request clarification or add additional context in comments.

Comments

0

You could define a (immutable) global variable which stores the reference of the functions:

# testcases.py

# ...

foos = foo_1, foo_2 # after the last foo_* function


# main.py
from testcases import foos

foo_1 = foos[0]

foos[1]() # call of foo_2

Alternatively use the dir built-in function to "look" at the content of the target "import":

import testcases


foos_ = {
    attr_name: getattr(testcases, attr_name.removeprefix('foo_'))
    for attr_name in dir(testcases)
    if attr_name.startswith('foo_')
    }

# examples of use-cases
foo_2 = foos_['2']

foos_['1']()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.