Skip to content

How to deal with global variables across modules in pytest? #11982

Answered by nicoddemus
TheVamp asked this question in Q&A
Discussion options

You must be logged in to vote

@RonnyPfannschmidt's answer is to the point, to complement, just change your code from:

def main():
    ...
    args, unknown = parser.parse_known_args()
    ...

if __name__ == "__main__":
    main()

To:

def main(argv):
    ...
    args, unknown = parser.parse_known_args(argv[1:])
    ...

if __name__ == "__main__":
    main(sys.argv)

This way you can easily pass the argument directly on each test, instead of manipulating sys.argv.

You will also need to do the same for the configuration and each function.

This pattern of "passing things instead of accessing globals" is considered good practice and aids in testing. Using globals might seem convenient at first, but globals have many drawba…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@nicoddemus
Comment options

Answer selected by TheVamp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants